Reputation: 203
When I attempt to convert one byte of hex into a char string I find that it takes 3 bytes. I am using Visual Studio 2013.
If I have less than 3 bytes I get an error: "Stack around the variable 'str' was corrupted."
What am I doing wrong? Surely the hex value 0xF1 should fit into char str[1]
? Why should I have to declare a 3 byte array to assign a 1 byte value?
char str[3];
sprintf(str, "%02X", 0xF1);
The content of str
is 0x0026fd18 "F1"
Upvotes: 0
Views: 197
Reputation: 6857
The issue is that's trying to print "F1" into the string followed by a null terminator - this would be three bytes. That's the whole point of the sprintf function - it formats the input into a readable string. If you're trying to simply assign the hex value of 0xF1 to a char, you would do it like this:
char str = (char)0xF1
Upvotes: 2