tags:

views:

59

answers:

3

Given a char, how to convert this char to a two digit char, which is the hex value of the binary presentation?

For example, given a char, it has a binary presentation, which is one byte, for example, 01010100, which is 0x54.....I need the char array of 54.

+4  A: 

Actually it would be:

char c = 84;
char result[3];
sprintf(result,"%02x",c);
icemanind
A: 

The following code, using snprintf() should work:

#include <stdio.h>
#include <string.h>

int main()
{
  char myChar = 'A'; // A = 0x41 = 65
  char myHex[3];
  snprintf(myHex, 2 "%02x", myChar);

  // Print the contents of myHex
  printf("myHex = %s\n", myHex);
}

snprintf() is a function that works like printf(), except that it fills a char array with maximum N characters. The syntax of snprintf() is:

int snprintf(char *str, size_t size, const char *format, ...)

Where str is the string to "sprint" to, size is the maximum number of characters to write (in our case, 2), and the rest is like the normal printf()

Frxstrem
+1  A: 

This is all far to easy readable :-)

#define H(x) '0' + (x) + ((x)>9) * 7
char c = 84;
char result[3] = { H(c>>4), H(c&15) };
drhirsch