Eric Horng Eric Horng - 8 months ago 99
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:


But I need it to look like this:


The algorithm I used was this:

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!

Answer Source

Consider the following code:

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

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


        printf("%02X ",hexBuffer[i]);


    return 0;

Use just a simple statement to convert int to byte buffer


You can use 8 instead of 4 while print the loop