Given a string of hex values i.e. e.g. "0011223344" so that's 0x00, 0x11 etc.
How do I add these values to a char array?
Equivalent to say:
char array[4] = { 0x00, 0x11 ... };
Given a string of hex values i.e. e.g. "0011223344" so that's 0x00, 0x11 etc.
How do I add these values to a char array?
Equivalent to say:
char array[4] = { 0x00, 0x11 ... };
You can't fit 5 bytes worth of data into a 4 byte array; that leads to buffer overflows.
If you have the hex digits in a string, you can use
sscanf()
and a loop:Note that printing the string starting with a zero-byte requires care; most operations terminate on the first null byte. Note that this code did not null-terminate the buffer; it is not clear whether null-termination is desirable, and there isn't enough space in the buffer I declared to add a terminal null (but that is readily fixed). There's a decent chance that if the code was packaged as a subroutine, it would need to return the length of the converted string (though you could also argue it is the length of the source string divided by two).
I would do something like this;
First, your question isn't very precise. Is the string a
std::string
or achar
buffer? Set at compile-time?Dynamic memory is almost certainly your answer.
Then, you can walk through the input, and assign it to the array.
Let's say this is a little-endian ascii platform. Maybe the OP meant "array of char" rather than "string".. We work with pairs of char and bit masking.. note shiftyness of x16..
and function encode() is defined...
This approach floats around elsewhere, it is not my original work, but it is old. Not liked by the purists because it is non-portable, but extension would be trivial.
If the string is correct and no need to keep its content then i would do it this way:
EDIT 1: sorry, i forget to calculate with the letters A-F (a-f)
EDIT 2: i tried to write a more pedantic code:
Testing:
Result: