I have an array of unsigned char which contains hex values. I would like to show it in the logs and in order to do it I need to convert it into a string.
Obviously if I directly try to use the character array as a string I get gibberish as is it interpreted as ASCII (e.g., it will be rendered as: "\xfê)Z+’\x2". Ideally I want to show the raw hex values without them being interpreted.
I have tried to copy it into a string but have not been successful. I am going to present what I have tried and the results that I got:
//My starting data type is unsigned char *
unsigned char* index = Block_data.Index;
//I convert it to const char* since most functions I could find for this type of
//conversion require a const char *, if this step can be avoided: I will do that
const char* indexc1 = reinterpret_cast<const char*>(index);
char outVal[9]; //allocate target buffer space
sprintf_s(outVal, "%9x", indexc1); //copy to target. This manages to copy the
// address of indexc1 and not its contents
sprintf_s(outVal, "%9x", *indexc1); //This gets one character from the
// address
sscanf_s(indexc1, "%9x", outVal); //This gets empty string
I feel that the answer may be quite simple but after some research I tried the above and have not been successful. Since I am running out of ideas (I tried few similar things as above) I am turning to the community for some help on this.
Your question is not very clear but I am assuming you want to build a string showing , in hex, the values of the first four bytes pointed to by index
.
The code could be:
char outVal[9];
sprintf(outVal, "%02X%02X%02X%02X", index[0], index[1], index[2], index[3]);
Do not try this with char *
pointer, that could lead to undefined behaviour. It relies on index
being unsigned char *
.
If you want to print many more bytes, then you can switch to a loop, for example:
std::vector<char> outVal( 2 * len + 1 );
for (size_t i = 0; i < len; ++i)
sprintf(&outVal[i * 2], "%02X", index[i]);
// OutputDebugString(&outVal[0]);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments