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

Qt QString add null terminator



  • How do you add a null terminator at the end of a QString? I'm sending data across the network and the receiving device expects one.


  • Moderators

    Hi, and welcome!

    @ConductedForce said in Qt QString add null terminator:

    How do you add a null terminator at the end of a QString? I'm sending data across the network and the receiving device expects one.

    In ASCII, the null-terminator is the null character, 0x00. It is represented as the '\0' literal in C/C++.

    Note: Technically, you send a byte array across the network; you don't send a text string.

    First, convert your QString to a QByteArray. Then, append a '\0' character to the end of the byte array. Then, send your byte array.



  • @JKSH
    Since this topic is marked as solved now anyway, I feel like observing:

    First, convert your QString to a QByteArray. Then, append a '\0' character to the end of the byte array. Then, send your byte array.

    Actually, according to me, you could skip appending that \0 character. When you have a QByteArray, QByteArray::data() is (surprisingly) always NUL-terminated, with the \0 being an additional character at the end (https://doc.qt.io/qt-5/qbytearray.html#data)! So, you can actually send QByteArray::size() + 1 bytes from data() and save on extending the byte array :)


  • Moderators

    @JonB said in Qt QString add null terminator:

    you could skip appending that \0 character. When you have a QByteArray, QByteArray::data() is (surprisingly) always NUL-terminated, with the \0 being an additional character at the end (https://doc.qt.io/qt-5/qbytearray.html#data)! So, you can actually send QByteArray::size() + 1 bytes from data() and save on extending the byte array :)

    Good catch!


Log in to reply