Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Error in QString.toUInt/Int/Double : Conversion fails



  • Hello, I'm receiving data over serial port like this: CH0:0x20FC0C05and splitting it in form like this: sep: ("CH0:0", "20FC0C05")

    I can split further and copy the data into another string variable data: "20FC0C05". The problem comes when I'm trying to use data.toUInt function. It always returns 0 and I'm not able to figure it out.

    Code snippet:

    if(line != NULL)
                {
                    //qDebug() << "line: " << line;
                    QStringList sep = line.split('x');
                    QString data;
                    //qDebug() << "sep: " << sep;
                    if(sep.at(0).startsWith("CH0"))
                    {
                        qDebug() << "sep: " << sep;
                        data.append(sep.takeLast());
                        qDebug() << "data: " << data << data.toUInt(&ok, 10) << ok;
                        //qDebug() << "sep: " << sep.takeLast().toInt(&ok,10);
                        //ch0_array[ch0_index] = sep.takeLast().toDouble();
                        //ch0_index += 1;
                        //qDebug() << "ch0: " << ch0_array;
                    }
                }
    

    Output preview:

    sep:  ("CH0:0", "20FB3500")
    data:  "20FB3500" 0 false
    sep:  ("CH0:0", "20FA040D")
    data:  "20FA040D" 0 false
    sep:  ("CH0:0", "20F88105")
    data:  "20F88105" 0 false
    sep:  ("CH0:0", "20FF240A")
    data:  "20FF240A" 0 false
    sep:  ("CH0:0", "2105C003")
    

    I've also tried toInt and toDouble functions but the result looks the same. If anyone has idea whats going on here, that'll be great.



  • I think you should use data.toUInt(&ok, 16). Because you are using hex data.



  • I think you should use data.toUInt(&ok, 16). Because you are using hex data.



  • @Ketank16 said in Error in QString.toUInt/Int/Double : Conversion fails:

    data.toUInt(&ok, 10)

    It looks like you're using the wrong base, don't you? You need to provide the base the value is (i.e. 16 in your example) not the base the value will be converted to. See example in the documentation.



  • @Pablo-J-Rogina Oh that was pretty quick and thank you. That was a bit confusing for me to understand, but the link you've shared is very useful. Thanks.


Log in to reply