QByteArray returned by QSerialPort readAll() method is always null terminated ?



  • Hi,

    I am using QSerialPort readAll() to receive data in a QByteArray.

    My question is QbyteArray always adding null termination at the end ? This is what documention says:

    "int QByteArray::size() const

    Returns the number of bytes in this byte array.

    The last byte in the byte array is at position size() - 1. In addition, QByteArray ensures that the byte at position size() is always '\0', so that you can use the return value of data() and constData() as arguments to functions that expect '\0'-terminated strings. If the QByteArray object was created from a raw data that didn't include the trailing null-termination character then QByteArray doesn't add it automaticall unless the deep copy is created"

    regards
    Ankur


  • Qt Champions 2016

    @ankurtyagi

    My question is QbyteArray always adding null termination at the end ?

    Yes, it does (when having its own data, see below for more explanation).

    The last byte in the byte array is at position size() - 1.

    Again, if we are talking of a byte array that has its own data, then the answer is, no - the last byte is positioned at QByteArray::size(). The byte array will allocate one more byte for the termination, but size() will return whatever you put in it (without the last "\0").

    If the QByteArray object was created from a raw data that didn't include the trailing null-termination character then QByteArray doesn't add it automaticall unless the deep copy is created

    As expected. If you use QByteArray::fromRawData the data is not really copied, so the byte array will not do anything on it. Unless you call a non-const function that will cause deep copying to occur, and when that does the byte array will add the termination symbol to its own copy of the data.

    Kind regards.



  • Thanks for the answer


Log in to reply
 

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