سؤال

I'm attempting my hand at creating a UDP terminal (custom) using Qt - Does anyone know if there's a widget or class for handling the conversion of the IP address from ASCII to numeric (hex) or do I have to write that myself? Basically "192.168.1.1" -> "0xC0A80101". I'm not opposed to writing it, just want to know if anyone knows if it already exists. Tried searching, not much luck. Thanks all

هل كانت مفيدة؟

المحلول

The key class here is QHostAddress as follows:

main.cpp

#include <QHostAddress>

#include <QTextStream>
#include <QString>

int main()
{
    QTextStream standardOutput(stdout);
    // You could use this, too:
    // standardOutput.setIntegerBase(16);
    // standardOutPut.setNumberFlags(QTextStream::ShowBase);
    quint32 ipAddress = QHostAddress("192.168.1.1").toIPv4Address();
    QString hexIpAddress = QString::number(ipAddress, 16);
    QString prefixedUppercaseHexIpAddress = QString("0x%1")
                                            .arg(uppercaseHexIpAddress);
    standardOutput << prefixedUppercaseHexIpAddress;
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core network
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

0xC0A80101

نصائح أخرى

Use QHostAddress to parse string IP representation and convert it to number. Use QString::number to convert number to hex string. See this one-liner:

qDebug() << QString::number(QHostAddress("192.168.1.1").toIPv4Address(), 16);

Output: "c0a80101"

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top