Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to convert (const std::vector<unsigned char>& vchIn) to QByteArray?
Forum Update on Monday, May 27th 2025

How to convert (const std::vector<unsigned char>& vchIn) to QByteArray?

Scheduled Pinned Locked Moved Solved General and Desktop
7 Posts 6 Posters 4.4k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • I Offline
    I Offline
    Infinity
    wrote on last edited by
    #1

    I have a function from a library which requires a const std::vector<unsigned char> as the second argument. The function declaration looks like this:

    bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet);
    

    My first parameter is a QByteArray and I would like to have the result also in a QByteArray. How can I convert const std::vector<unsigned char>& vchIn into a QByteArray? Or even better, how could I change the function below, that it returns a QByteArray?

    static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    
    bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
    {
        // Skip leading spaces.
        while (*psz && isspace(*psz))
            psz++;
        // Skip and count leading '1's.
        int zeroes = 0;
        int length = 0;
        while (*psz == '1') {
            zeroes++;
            psz++;
        }
        // Allocate enough space in big-endian base256 representation.
        int size = strlen(psz) * 733 /1000 + 1; // log(58) / log(256), rounded up.
        std::vector<unsigned char> b256(size);
        // Process the characters.
        while (*psz && !isspace(*psz)) {
            // Decode base58 character
            const char* ch = strchr(pszBase58, *psz);
            if (ch == nullptr)
                return false;
            // Apply "b256 = b256 * 58 + ch".
            int carry = ch - pszBase58;
            int i = 0;
            for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); (carry != 0 || i < length) && (it != b256.rend()); ++it, ++i) {
                carry += 58 * (*it);
                *it = carry % 256;
                carry /= 256;
            }
            assert(carry == 0);
            length = i;
            psz++;
        }
        // Skip trailing spaces.
        while (isspace(*psz))
            psz++;
        if (*psz != 0)
            return false;
        // Skip leading zeroes in b256.
        std::vector<unsigned char>::iterator it = b256.begin() + (size - length);
        while (it != b256.end() && *it == 0)
            it++;
        // Copy result into output vector.
        vch.reserve(zeroes + (b256.end() - it));
        vch.assign(zeroes, 0x00);
        while (it != b256.end())
            vch.push_back(*(it++));
        return true;
    }
    
    1 Reply Last reply
    0
    • Christian EhrlicherC Offline
      Christian EhrlicherC Offline
      Christian Ehrlicher
      Lifetime Qt Champion
      wrote on last edited by
      #2

      See QByteArray(const char *data, int size)

      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
      Visit the Qt Academy at https://academy.qt.io/catalog

      1 Reply Last reply
      5
      • fcarneyF Offline
        fcarneyF Offline
        fcarney
        wrote on last edited by fcarney
        #3

        @Christian-Ehrlicher 's solution is the way to go. I got complicated on mine:

                std::vector<unsigned char> source = {'a'+0,'a'+1,'a'+2,'a'+3,'a'+4,'a'+5,'a'+6,'a'+7,'a'+8,'a'+9};
                QByteArray output; // empty byte array
                for(auto val: source){
                    output.push_back(val);
                }
        
                // or use something from algorithm
                QByteArray output2;
                std::copy(source.begin(), source.end(), std::back_inserter(output2));
        
                qInfo() << output;
                qInfo() << output2;
        

        C++ is a perfectly valid school of magic.

        1 Reply Last reply
        2
        • I Offline
          I Offline
          Infinity
          wrote on last edited by
          #4

          That is how I ended up doing it:

          QByteArray encodeInput = "Hello world";
          std::vector<unsigned char> encodeResultVector;
          encodeResultVector.reserve(encodeInput.size());
          for(int i = 0; i < encodeInput.size(); ++i)
              encodeResultVector.push_back(static_cast<unsigned char>(encodeInput.at(i)));
          std::string encodeReslutStdString = EncodeBase58(encodeResultVector);
          QByteArray encodedArray(encodeReslutStdString.c_str(), encodeReslutStdString.length());
          
          qDebug() << "encode input  :" << encodeInput;
          qDebug() << "encoded array :" << encodedArray;
          
          QByteArray decodedArray;
          std::vector<unsigned char> vchRet;
          bool ret = DecodeBase58(encodedArray.constData(), vchRet);
          decodedArray.reserve(vchRet.size());
          for(size_t i = 0; i < vchRet.size(); ++i)
              decodedArray.append(vchRet.at(i));
          
          qDebug() << "decoded array :" << decodedArray;
          
          encode input  : "Hello world"
          encoded array : "JxF12TrwXzT5jvT"
          decoded array : "Hello world"
          
          1 Reply Last reply
          0
          • nooneN Offline
            nooneN Offline
            noone
            wrote on last edited by
            #5
            std::vector<unsinged char> bson = ....
            QByteArray qbson(reinterpret_cast<const char*>(bson.data()), bson.size());
            
            1 Reply Last reply
            0
            • Q Offline
              Q Offline
              QtCoder87
              wrote on last edited by
              #6

              Can I ask why qt did not insert the static Function fromStdVectorUint8t to QByteArray?
              you can make QString from 4 Basic_string variants char, char16_t, char32_t and wchar_t

              why not bytearry from Std::vector<uint8_t> ?

              JKSHJ 1 Reply Last reply
              0
              • Q QtCoder87

                Can I ask why qt did not insert the static Function fromStdVectorUint8t to QByteArray?
                you can make QString from 4 Basic_string variants char, char16_t, char32_t and wchar_t

                why not bytearry from Std::vector<uint8_t> ?

                JKSHJ Offline
                JKSHJ Offline
                JKSH
                Moderators
                wrote on last edited by
                #7

                @QtCoder87 said in How to convert (const std::vector<unsigned char>& vchIn) to QByteArray?:

                why not bytearry from Std::vector<uint8_t> ?

                Mainly because there was little demand for it.

                It is very easy to and cheap to reinterpret a uint8_t array as a char array, so QByteArray::fromStdUInt8Vector(const std::vector<uint_8> &vector) wouldn't add much value. Just use QByteArray(const char *data, int size).

                Anyway, future code should not use uint8_t OR char. Instead, we should move towards std::byte.

                Qt Doc Search for browsers: forum.qt.io/topic/35616/web-browser-extension-for-improved-doc-searches

                1 Reply Last reply
                1

                • Login

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • Users
                • Groups
                • Search
                • Get Qt Extensions
                • Unsolved