开发者

How to get the binary presentation in hex value of a char

开发者 https://www.devze.com 2023-01-12 04:12 出处:网络
Given a char, how to convert this char to a two digit char, which is the hex value of the binary presentation?

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

For e开发者_Python百科xample, 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.


Actually it would be:

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


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) };


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()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号