Important: Please read the Qt Code of Conduct -

QByteArray comparator

  • I am working on application and ran across and issue I need some confirmation on. I have a byte array of data received from a device that can have values ranging from 0x00 - 0xFF. In my program, I have a statement as follow:

    QByteArray rcvd_buffer; // received data read from device

    if (rcvd_buffer[i] > 0xC8)
    The above logic is always true but my rcvd_buffer[i] value is a 5.
    Why is this the case? Do I have to cast rcvd_buffer[i] as a byte to have it worked properly?

  • well. gcc complains about it, but I don't know why yet..
    I'm doing some test.

  • just a thought... do you think it is because rcvd_buffer[i] is a char and characters can only be from 0-0x7F?

  • Certainly is something related to the conversion.
    I'm still looking for it..

    Someone else?

  • outch...

    0xC8 is negative if you compare it with a char...

    cast it to unsigned char and it will work:
    @if ((unsigned char) ba[1] > 0xC8)@

  • it looks like I have to cast my data to (quint8)rcvd_buffer[i] since my data can range from 0x00-0xFF... I thought that QByteArray should be an array of unsigned char instead of signed char.... I assume I will have to double check to see if me assigning negative values to rcvd_buffer[i] would error out as well... Please post if anyone has any insights...

  • I use this method of comparation QByteArray element with literal in Qt5.2.1:
    @if ( ans[startIndex+1].operator ==(0xFF) ) {/.../}

    it is wierd, but it works :)

  • Moderators

    Asazeus - you do realize that this is the same as
    @ if(ans[startIndex+1] == 0xFF)
    just uglier and less readable? There's almost never a reason to call operators explicitly.

    The problem is that == will work, but < or > will not in this case. It's a signed/unsigned problem as noted before.

Log in to reply