Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an int to a 2 byte hex value in C

Tags:

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?

like image 999
MBU Avatar asked Nov 03 '10 09:11

MBU


People also ask

What is the hex value stored for for 2 byte integer?

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.

How do you convert int to byte value?

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

How do you convert bytes to hexadecimal?

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.

Is a hex value 1 byte?

As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.


1 Answers

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'; } 
like image 94
Vicky Avatar answered Sep 21 '22 18:09

Vicky