[SOLVED]Accessing int form of QByteArray



  • Hi,

    I'm using Qserialport for capturing input data.My data is suppose to be in the format "abc-123"
    I'm storing the seial data in the QByteArray. The logic works and stores the data in QByteArray.

    My question is I wanna seperate the numbers from "abc-123" and access only int form as "123" which i'm not getting
    I tried the following code with which i'm getting seperate elements of array as follows. Can you please give a clue.
    Data a: 49
    Data b: 50
    Data c: 51

    @
    void MainWindow::readSerialConsole(){
    QByteArray cmpdata= "abc-";

    qint8 positionV;
    int a,b,c;
    QByteArray serialData= serialConsole->readAll();
    console->putData(serialData);
    if(serialData.contains(cmprpm)||serialData.contains(cmpspd)){
    
        if(serialData.contains(cmpdata))
            positionV=serialData.indexOf(cmpdata);
    
      
        positionV+=4;
        a=serialData.at(positionV++);
        b=serialData.at(positionV++);
        c=serialData.at(positionV);
    
        qDebug("Data a: %d ",a);
        qDebug("Data b: %d ",b);
        qDebug("Data c: %d ",c);
    
    }
    
    positionV=0;
    

    }@



  • Of course. Your byte array contains an array of characters that encode the text abc-123. Note that 1, 2, and 3 are characters in that text, not a value. The integer values of those characters happen to be 49, 50 and 51 respectively (as you can find in any ASCII table).

    So, you need to first isolate the part of the byte array that contains the number, and then interpret that part as a number. For instance:
    @
    //from your example line 15
    positionV+=4;

        QByteArray numberPart = serialData.mid(positionV, 3);
        int result = numberPart.toInt();
        qDebug() << "The value:" << result;
    

    @

    Alternatively, look into using QTextStream to read your data.



  • Hi Andre,

    Thanks for your reply.The problem is solved.

    bq. Alternatively, look into using QTextStream to read your data.

    Yep, Sure


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.