Eric Horng - 6 months ago 80
C Question

# Converting an int to uint8_t array HEX value

I'd like to take an int, and convert it into uint8_t array of hex numbers? The int is at maximum 8 bytes long in HEX after conversion. I was able to use a method that converts an int (19604) into a uint8_t array like this:

``````00-00-00-00-00-00-00-00-04-0C-09-04
``````

But I need it to look like this:

``````00-00-00-00-00-00-00-00-00-00-4C-94
``````

``````void convert_file_size_to_hex(long int size)
{
size_t wr_len = 12;
long int decimalNumber, quotient;
int i=wr_len, temp;

decimalNumber = size;
quotient = decimalNumber;
uint8_t hexNum[wr_len];
memset(hexNum, 0, sizeof(hexNum));

while(quotient != 0) {
temp = quotient % 16;
hexNum[--i] = temp;
quotient /= 16;
}
``````

How can I go about doing this? Should I use a different algorithm or should I try to bit shift the result? I'm kinda new to bit shifting in C so some help would be great. Thank you!

Consider the following code:

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

int main()
{
unsigned char hexBuffer[100]={0};
int n=19604;
int i;

memcpy((char*)hexBuffer,(char*)&n,sizeof(int));

for(i=0;i<4;i++)
printf("%02X ",hexBuffer[i]);

printf("\n");

return 0;
}
``````

Use just a simple statement to convert int to byte buffer

``````memcpy((char*)hexBuffer,(char*)&n,sizeof(int));
``````

You can use 8 instead of 4 while print the loop

Source (Stackoverflow)