Important: Please read the Qt Code of Conduct -

How can i convert hexadecimal to binary in qt?

  • Hi,
    How can i convert a hexadecimal to binary in qt?
    I am trying as below but its not giving correct binary returns 0 for any hexa value entered...

    I am reading hexadecimal as a string(actually this number resides inside a file, hence reading as a string)
    then converting this string into hexadecimal,
    then converting this to binary...
    the code as shown below...

    this function takes hexadecimal value as string then returns the binary corresponding value

    @ int FilterColl::BinVal(QString str)
    bool ok;

    int iVal=str.toInt(&ok,16);
    QString hexnum=QString::number(iVal,16);
    std::cout<<"THE HEX VALUE IS:"<<hexnum.toStdString()<<endl;
    bool ok1;
    cout<<"THE BINARY VALUES IS:"<<iVal<<endl;
    return iVal;
    cout<<"CONVERSION FAILED !!!!!!!!!!!!!"<<endl;
    return (iVal);

  • hexnum.toInt(&ok1,2); will always fail because the number is in hex (for eg. "0xAB11"),

    since you are returning an int in the function.. it does not matter how it is converted from string.
    just return the number in hex.

  • QString::to...() converts from a given base, QString::number() converts to a given base, thus <code>iVal = hexnum.toInt(&ok1, 2)</code> makes no sense, as you are trying to convert a hexadecimal number using base 2. In addition, your method has no return path for <code>ok1</code> beeing false.

    QString hexadecimalNumber = "0xDEADBEEF";

    bool ok = false;
    QString binaryNumber = QString::number(hexadecimalNumber.toLongLong(&ok, 16), 2);

    qDebug() << binaryNumber; // "11011110101011011011111011101111"

  • Thank u Lukas...
    And is there any standard function in Qt to perform AND operation on two strings of digit?

  • Thumb Lucas, In my mind, There is no direct method to perform "And" operation on two string-digit

  • [quote author="aurora" date="1331020035"]Thank u Lukas...
    And is there any standard function in Qt to perform AND operation on two strings of digit? [/quote]

    I don't think so. <code>+</code> always returns a string which is the result of concatenating both strings. If you want to add them you will have to convert it to some numeric datatype, perform the addition and convert it back to a string.

  • Always good to know how to do this stuff manually. So here is a link.
    "How to convert hex to decimal manually and back":

  • Banned

    This post is deleted!

Log in to reply