I have to convert one line from ruby to Qt C++
I 开发者_开发技巧need help from some one to convert the following line of code from ruby to qt c++:
KEY = %w(30 81 9F 30 0D 06 09 2A 86 48 86 F7 0D 01 01 01 05 00 03 81 8D 00).map{|s| s.hex}.pack('C*')
Here's what the Ruby code does:
- Create an array of strings,
["30", "81", "9F", ... "8D", "00" ]
. - Convert each hexadecimal string in the array to an integer:
[48, 129, 159, ... 141, 0]
- Use
Array#pack
to turn the array into a single binary string of unsigned 8-bit integers.
If a simple C array will do:
unsigned char KEY[22] = { 0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06... };
If you need a QByteArray:
QByteArray KEY("\x30\x81\x9F\x30\x0D\x06...", 22);
QByteArray key = QByteArray::fromHex(QByteArray("30 81 9F 30 0D 06 09 2A 86 48 86 F7 0D 01 01 01 05 00 03 81 8D 00").replace(' ', QString()));
Quick explanation:
QByteArray("30 81 9F 30 0D 06 09 2A 86 48 86 F7 0D 01 01 01 05 00 03 81 8D 00")
creates temporary QByteArray with your key as string
.replace(' ', QString())
removes all spaces in temporary QByteArray, so it contains only characters 0..F
QByteArray::fromHex()
converts hex-encoded QByteArray into QByteArray containing unsigned 8-bit integers (i.e. C++ char type). It means that it takes every pair of hex digits from original QByteArray ( for example "41") and converts it to integer ("41" will be converted to 65 = 4*16 + 1) and appends this value into new QByteArray.
If you need key as a "const char *" you can use QByteArray::constData() method, but you have to remember that the pointer returned by this method is valid only as long as original QByteArray is valid (quote from documentation: "as long as the byte array isn't reallocated or destroyed"). So if you need to store the key data, keep it as QByteArray or make a copy of const char * returned by constData().
char KEY[] = {
48, 129, 159, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 3, 129, 141, 0
};
The result is something slightly different, a flat array of byte values. It would certainly be possible to make an array of 1-character-string object references, but it would not be likely to be useful.
精彩评论