11

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

SamuelNLP
  • 4,038
  • 9
  • 59
  • 102

2 Answers2

14

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...

Community
  • 1
  • 1
hyde
  • 60,639
  • 21
  • 115
  • 176
  • well I need it. I get `error: invalid static_cast from type 'unsigned char [10]' to type 'char*'` – SamuelNLP Mar 11 '13 at 11:25
  • My unedited answer used `static_cast`, here's linked question for why it does not work: http://stackoverflow.com/questions/10151834/why-cant-i-static-cast-between-char-and-unsigned-char – hyde Mar 11 '13 at 11:41
1

As it says, the argument passed to fromRawData should be a const char*, not an unsigned char*. You could make your array be an array of const char:

const char buf[10];

The array can be converted to a pointer to its first element which will a const char*, exacly as fromRawData expects.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • should I create a new `char *array` and pass the data from `buf` first to the array and then convert it? – SamuelNLP Mar 11 '13 at 11:23