I need to convert an int to a 2 byte hex value to store in a char array, in C. How can I do this?
A single hexadecimal digit (0 - F => 0000 - 1111 ) represents 4 binary bits. Therefore, a 16 bit memory address would require 4 hexadecimal digits, 0000-FFFF. This is commonly referred to as two bytes, or one “word”. A 16 bit memory address would support 64K of memory.
The byteValue() method of Integer class of java. lang package converts the given Integer into a byte after a narrowing primitive conversion and returns it (value of integer object as a byte).
To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st . This is a relatively slower process for large byte array conversion.
As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.
If you're allowed to use library functions:
int x = SOME_INTEGER; char res[5]; /* two bytes of hex = 4 characters, plus NULL terminator */ if (x <= 0xFFFF) { sprintf(&res[0], "%04x", x); }
Your integer may contain more than four hex digits worth of data, hence the check first.
If you're not allowed to use library functions, divide it down into nybbles manually:
#define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i) int x = SOME_INTEGER; char res[5]; if (x <= 0xFFFF) { res[0] = TO_HEX(((x & 0xF000) >> 12)); res[1] = TO_HEX(((x & 0x0F00) >> 8)); res[2] = TO_HEX(((x & 0x00F0) >> 4)); res[3] = TO_HEX((x & 0x000F)); res[4] = '\0'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With