🔒 Locked
Function for return hexadecimal code?
Advertisement
Original Post
Why this initialization?
Anyway, Boost Format does the trick quite nicely:
Quote:
Original post by Sharlin ... char buf[5] = {};...
Anyway, Boost Format does the trick quite nicely:
std::string CharToHex( char ch ){ return boost::str(boost::format("%x") % ch);}std::string CharToHex( char ch ){ const int size = 5; char buf[size] = {}; verify( size > sprintf( buf, "0x%02x", ch & 0xFF )); return buf;}The above is better, actually, since:
1° It explicitly states what the maximum size that can be written into the buffer, thus reminiding maintenance programmers that it is hazardous ot change the format string.
2° It does not use "magic" literals that determine the size of the buffer: the literal only appears in one place, and its named value is used elsewhere.
3° Should someone change the format of the sprintf call without adapting the buffer size, an assert would usually fail when the buffer is overwritten.
Besides, I cannot remember if sizeof("0xFF") is legal or not, but if it is, it should be used in place of the "5".
What about this :)
It is, but it returns sizeof(const char*).
std::string CharToHex( char ch ){ char buf[] = "0xFF"; verify( sizeof(buf) > sprintf( buf, "0x%02x", ch & 0xFF )); return buf;}Quote:
Besides, I cannot remember if sizeof("0xFF") is legal or not, but if it is, it should be used in place of the "5".
It is, but it returns sizeof(const char*).
Quote:
Original post by Anonymous Poster
Lets try that again....
one single-threaded safe func:
code removed
should be loads faster and safer :)
Too bad that's not standard C or C++. Oh, and I wouldn't call it safe.
[Hint: The standard doesn't specify character sets. And never return a pointer to a local variable.]
If you just want to output the value as hex, look into stream manipulators.
You could do it with stream manipulators anyway if you want to save the new string:
But that's rather overkill. Let's build the string "manually", but still use an actual string, and have simple logic:
You could do it with stream manipulators anyway if you want to save the new string:
std::string toHex(char c) { std::stringstream ss; ss << std::hex << c; return ss.str();}But that's rather overkill. Let's build the string "manually", but still use an actual string, and have simple logic:
std::string toHex(char c) { static const char symbols[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; // we don't want a trailing \0 std::string result(2, '\0'); result[0] = symbols[c >> 4]; result[1] = symbols[c & 15]; return result;}
result[0] = symbols[c >> 4];Careful -- c could be negative. You should do this:
result[0] = symbols[(c >> 4) & 15];
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement