1

Is there a library function that takes in an integer and converts it to a single-byte hexadecimal or binary number?

For example, if I passed it the input of 64, it would output 0x40.

Kobi
  • 1,395
  • 4
  • 17
  • 23

4 Answers4

2

For hex numbers, you can use sprintf:

char buff[80];
sprintf(buff, "0x%02x", 64);
eduffy
  • 39,140
  • 13
  • 95
  • 92
  • Does buff have to be an array? Can't it not be represented in one byte. For example, char a = 0x45. – Kobi Mar 09 '12 at 15:56
  • 1
    I suppose what I was really looking for was how to change an int to a char, which is easier than expected. – Kobi Mar 09 '12 at 16:00
2

An int is an int, whether it is 0x40 or 64; the data representation of the two is exactly the same (10000000...011111111). If you are asking how it would be represented in a char array, you'd use sprintf. The simplest way is sprintf(buf, "%#x", 64).

jcai
  • 3,448
  • 3
  • 21
  • 36
1

Internally, integers are already represented as binary. You can display a number as hexadecimal using the %x format string (%#02x will fit your example best).

See this question regarding binary, for which there isn't a built-in format string specifier.

Community
  • 1
  • 1
ezod
  • 7,261
  • 2
  • 24
  • 34
1

In C the int type's size depends upon implementation. Normally, it will be 4 bytes long, and thus impossible to storing in a single byte without losing important information.

If you use a char or int8_t then you will have a single byte. Bytes are binary internally and always will be. So anytime you want to do anything with your byte, you must do it in binary.

Hexadecimal vs binary vs base 10 is a display decision. So if you accept those as input, you will have to convert a string into a single byte for storage in memory. When you display them, you will have to convert to the desired display format.

Using sprintf works for display. Use strtol for input.

Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73