0

I have a QString

string = "131865EDC62E4AC5131865EDC62E4AC5"

which is 16 hex-numbers. I need to convert this to something like

const unsigned char s[] = {0x13, 0x18, 0x65, 0xED, 0xC6, 0x2E, 0x4A, 0xC5, 0x13, 0x18, 0x65, 0xED, 0xC6, 0x2E, 0x4A, 0xC5}

How should I do this? I tried different methode like QString::toInt, QString::toUlong, QString::toLatin1, but they don't do what I want.

yangsunny
  • 656
  • 5
  • 13
  • 32

1 Answers1

-1

Is that what you want ?

QString string = "131865EDC62E4AC5131865EDC62E4AC5";

QString sub = string.left(2) ;
QList<unsigned char> list;
while(sub != "")
{
    bool bStatus = false;
    unsigned int res = sub.toUInt(&bStatus,16);
    if (bStatus)
        list.append(res);

    string = string.mid(2);
    sub = string.left(2) ;
}

QVector<unsigned char> vect = list.toVector();
const unsigned char* s = vect.constData();

for (auto it = vect.begin(); it != vect.end(); ++it)
    printf("%#x ",*it);
Gwen
  • 1,436
  • 3
  • 23
  • 31
  • Not quite, as I mentioned, I need the result in `const unsigned char`, not a `QList`. And secondly, values should stay in hex like `0x13 or 13`, not as `int` – yangsunny Mar 23 '16 at 10:37
  • I added the conversion to `const unsigned char*` (you need to keep the `vect` object as long as you want to use `s`, or to copy the data). Your data is stored as unsigned int, you can't choose between an hexadecimal or a decimal representation. With the printf in hexadecimal format, the output is: `0x13 0x18 0x65 0xed 0xc6 0x2e 0x4a 0xc5 0x13 0x18 0x65 0xed 0xc6 0x2e 0x4a 0xc5` – Gwen Mar 23 '16 at 11:50
  • Maybe I misunderstood what you want: do you want an array of hexadecimal values `{0x13, 0x18, ...}` or an array of hexadecimal representations of unsigned int values `{"0x13", "0x18", ...}` ? – Gwen Mar 23 '16 at 12:17
  • I want an array of size 16(32 hexnumbers in pair of 2) with the actualy hex values. – yangsunny Mar 23 '16 at 13:13
  • There is no type "hex value" or "hex number". 0x13 is the hexadecimal representation of the integer 19, or of the character '\r'. 19 and '\r' shares the same internal representation: 0x13. You need to define more precisely what you want: either a numeral value with an internal representation of 0x13 (that could be interpreted as int 19 or char '\r'), or a string containing the chars '0', 'x', '1', '3'. Or something else. – Gwen Mar 23 '16 at 14:08