How to convert std::vector<uint8_t> to QByteArray?

11,202

You need to cast buf.data() instead of buf:

QByteArray* img = new QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());
Share:
11,202
goGud
Author by

goGud

C++ and Qt developer

Updated on July 24, 2022

Comments

  • goGud
    goGud 5 months

    I am trying to create QByteArray from std::vector.. I tried;

    std::vector<uint8_t> buf;
    QByteArray img = new QByteArray(reinterpret_cast<const char>(buf), buf.size());
    

    However it gives error;

    error: invalid cast from type 'std::vector<unsigned char, std::allocator<unsigned char> >' to type 'const char'
    
  • johimi over 7 years
    Note .data() is only available in C++11 and later. If your compiler doesn't support this, use &buf[0].
  • goGud
    goGud over 7 years
    when I use buf.data() it says error: cast from 'unsigned char*' to 'const char' loses precision
  • goGud
    goGud over 7 years
    ohh.. my mistake, I didnt use char pointer.. thank you very much
  • akira hinoshiro
    akira hinoshiro over 2 years
    I personally do avoid new and delete wherever I can. You can do on modern compilers like this: [auto img = QByteArray(reinterpret_cast<const char*>(buf.data()), buf.size());]