Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unsigned char[10] to QBytearray;

I've seen a lot o questions around this, but so far none worked for me.

I've tried the 2 most common answers but I get the same error.

being but an unsigned char buf[10];

this,

QByteArray databuf;
databuf = QByteArray::fromRawData(buf, 10); 

or this,

QByteArray databuf;
databuf = QByteArray(buf, 10);

got me the same error,

error: invalid conversion from 'unsigned char*' to 'const char*' [-fpermissive]

any advice?

thank you

like image 844
SamuelNLP Avatar asked Mar 11 '13 11:03

SamuelNLP


People also ask

Can we increment unsigned char?

Yes, it is possible to increment it, just like any number, and it's also faster.

Can you cast unsigned char to char?

However, from i=128:255 the chars and the unsigned chars cannot be casted, or you would have different outputs, because unsigned char saves the values from [0:256] and char saves the values in the interval [-128:127]).

What is QByteArray?

QByteArray is the Qt class to store a array of bytes. It is analogous to a char *. Unlike a QString, a QByteArray has no encoding information and makes no attempt to decode bytes into characters.


1 Answers

It's just signedness issue, so this should work:

databuf = QByteArray(reinterpret_cast<char*>(buf), 10);

Or with legacy C-style cast:

databuf = QByteArray((char*)buf, 10);

(Here's one of many many discussions about which you should use.)

Easier alternative is to remove unsigned from declaration of buf, if you don't need it there for some other reason.

Note, that if you use that fromRawData method, it does not copy the bytes, so better be sure buf won't go out of scope too soon. If unsure, do not use it...

like image 89
hyde Avatar answered Sep 20 '22 22:09

hyde