Hex String Function

• 06-26-2011
dhuan
Hex String Function
What this function (hex_str) does is, it receives a 1-byte char as argument, and returns its hex representation as string.

I'd like some tips on how to improve my code.

Code:

```#include <iostream> #include <string> #include <stdio.h> using namespace std; char first_4_bits_hex(char value) {     char hex_value[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};     int count = 0;     for(int x = 1; x <= 8; x = (x << 1))     {         if(value & x)             count += x;     }     return hex_value[count]; } string hex_str(char value) {     string return_str="00";     return_str[1] = first_4_bits_hex(value);     value = value >> 4;     return_str[0] = first_4_bits_hex(value);     return return_str; } int main() {     string str = hex_str(0x10);     cout<<str;     return 0; }```
• 06-27-2011
iMalc
The effect of your for loop is the same as masking value with 0x0F.
Also, you could shorten that char array initialisation to just "0123456789ABCDEF" 'i','n','s','t','e','a','d'.
That function can be a one-liner when you know enough C++.
• 06-27-2011
dhuan
Quote:

The effect of your for loop is the same as masking value with 0x0F.

Quote:

Also, you could shorten that char array initialisation to just "0123456789ABCDEF" 'i','n','s','t','e','a','d'.
How could I not have seen it before. Thanks. I'll apply it to my code.

Quote:

That function can be a one-liner when you know enough C++.
Yeh, I'm sure there's many ways of doing this much better than what I did, that's why I posted here, the code's working, but maybe with the help of veterans I could improve it.
• 06-27-2011
dhuan
Bump
• 06-27-2011
iMalc
Whilst I wont write the exact answer for you, this should demonstrate how it can be done:
Code:

`return "0IVXLCDM"[numeral & 0x07];`