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

How to generate a QByteArray from std::string which contains \0x00?



  • The function m_cryptoNewKeyResponse->public_key() returns a std::string which actually contains '\0x00' characters.

    qDebug() << "public key length:" <<  m_cryptoNewKeyResponse->public_key().length();
    // Oputpu: public key length: 88
    QByteArray publicKey(m_cryptoNewKeyResponse->public_key().data());
    qDebug() << "public key length:" <<  publicKey.length();
    // Output: public key length: 18
    qDebug() << "public key raw:" <<  publicKey;
    // Output: public key raw: 3056301006072a8648ce3d020106052b8104
    

    How can I generate a QByteArray which also contains the '\0x00'? As you can see above, the QBytearray cuts the off everything which is after the first '\0x00'.



  • @Infinity std::string::data() return as const char * so QByteArray(const char *) will stops a first '\0' found.
    To do it right use auto publicKey = QByteArray(m_cryptoNewKeyResponse->public_key().data(), m_cryptoNewKeyResponse->public_key().length())

    See QByteArray() documentation


  • Moderators

    @Infinity said in How to generate a QByteArray from std::string which contains \0x00?:

    How can I generate a QByteArray which also contains the '\0x00'? As you can see above, the QBytearray cuts the off everything which is after the first '\0x00'.

    no it does not, qDebug however does.

    try

    qDebug() << "public key raw:" <<  publicKey.toHex(' ');
    


  • This the output of the qDebug()

    public key length: 88
    public key length: 18
    public key raw hex: "30 56 30 10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04"

    That is the output with

    qDebug() << "public key raw:" <<  publicKey.toHex(' ');
    // Output: public key raw hex: "30 56 30 10 06 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04"
    

    Why does

    m_cryptoNewKeyResponse->public_key().length();
    //Output: public key length: 18
    

    return 88 (which is correct)

    and:

    QByteArray publicKey(m_cryptoNewKeyResponse->public_key().data());
    qDebug() << "public key length:" <<  publicKey.length();
    //Output: public key length: 18
    

    return 18?


  • Moderators

    @Infinity probably an implicit conversation error.

    You said, that m_cryptoNewKeyResponse->public_key() returns an std::string?

    than try the following:

    QByteArray publicKey = QByteArray::fromStdString(m_cryptoNewKeyResponse->public_key());
    


  • @Infinity std::string::data() return as const char * so QByteArray(const char *) will stops a first '\0' found.
    To do it right use auto publicKey = QByteArray(m_cryptoNewKeyResponse->public_key().data(), m_cryptoNewKeyResponse->public_key().length())

    See QByteArray() documentation


Log in to reply