2

I just want to convert a byte to its ASCII character.

Here is the problem:

Lets suppose we have a character like below:

char a = 0x0b;

I just want to convert this to its hexadecimal ASCII character representation 'b' .

user0042
  • 7,691
  • 3
  • 20
  • 37

1 Answers1

4

Just use the appropriate I/O manipulator:

char a = 0x0b;
std::ostringstream oss;
oss << std::hex << (int)a;
    // ^^^^^^^^
char ascii = oss.str()[0];

See it working live here.


An alternative would be to use a simple table of characters:

char a = 0x0b;
char ascii = "0123456789abcdef"[a];

To extract values bigger than 0x0f use bit shifting and masking:

unsigned char a = 0xab;
const char* hexDigitTable = "0123456789abcdef";
char asciiDigit0 = hexDigitTable[a & 0x0f];
char asciiDigit1 = hexDigitTable[(a & 0xf0) >> 4];
std::cout << asciiDigit1 << asciiDigit0 << std::endl;

Here's the live example.


Note: I've been using unsigned char above to get rid of the compiler warning on initialization of a.

user0042
  • 7,691
  • 3
  • 20
  • 37