Reputation: 4152
I am new to c++ and still trying to feel my way in. I have attempted to adapt a function I have found on SO to convert my string into bytes as I need:
void hexconvert(const char *text, unsigned char bytes[])
{
int i;
int temp;
for (i = 0; i < 4; ++i) {
sscanf(text + 2 * i, "%2x", &temp);
bytes[i] = temp;
}
cout << bytes;
}
hexconvert("SKY 000.001\n", );
Issues I have are:
1) I am not sure how to amend the for loop to handle my string. 2) I am not sure what I should use as the input for the second parameter in the function.
Can anyone assist?
Thanks
Upvotes: 1
Views: 9782
Reputation: 2942
This is my suggested solution. I used it to encode a GUID as a byte array. It should achieve higher performance than having to do printf
on all the characters.
typedef unsigned char byte;
std::map<char, byte> char2hex =
{
{'0', 0x0},
{'1', 0x1},
{'2', 0x2},
{'3', 0x3},
{'4', 0x4},
{'5', 0x5},
{'6', 0x6},
{'7', 0x7},
{'8', 0x8},
{'9', 0x9},
{'a', 0xa},
{'b', 0xb},
{'c', 0xc},
{'d', 0xd},
{'e', 0xe},
{'f', 0xf}
};
void convertToBytes(const string &chars, byte bytes[])
{
for (size_t i = 0; i < chars.length() / 2; i++) {
byte b1 = (byte)(char2hex[chars[2*i]] << 4);
byte b2 = char2hex[chars[2*i+1]];
byte f = b1 | b2;
*(bytes + i) = f;
}
}
Remember that two ascii characters make up one byte, so for every pair of characters, I have to convert the first character to byte, then shift it up by 4 bits, then or it with the next character to get one byte.
Upvotes: 1
Reputation: 57749
To print a string as bytes:
const size_t length = data.length();
for (size_t i = 0; i < length; ++i)
{
unsigned int value = data[i];
std::cout << std::dec << std::fill(' ') << value
<< " (0x" << std::setw(2) << std::setfill('0') << std::hex << value << ')'
<< "\n";
}
Some important rules to remember:
1. Copy the character into an integer type variable, so that cout
doesn't print as character.
2. Bytes are unsigned.
3. When filling the width with 0 for hex, remember to reset it to space before printing decimal.
4. Use std::hex
for printing in hexadecimal, and remember to reset it with std::dec
afterwards (if you are printing in decimal afterwards).
See <iomanip>
.
Edit 1: C-Style
To use the C language style:
static const char data[] = "Hello World!";
const size_t length = strlen(data);
for (size_t i = 0; i < length; ++i)
{
printf("%3d (0x%02X)\n", data[i], data[i]);
}
The above assumes that data
is a character array, nul terminated.
Upvotes: 0