Reputation: 57
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
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!
Upvotes: 2
Views: 5925
Reputation: 1309
Use a union for this
union int_to_bytes {
int i;
uint8_t b[sizeof(int)];
};
union int_to_bytes test = { .i = 19604 };
int i = sizeof(test.b); // Little-Endian
while (i--)
printf("%hhx ", test.b[i]); // 0 0 4c 94
putchar('\n');
Upvotes: 0
Reputation: 167
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
Upvotes: 1
Reputation: 726559
Since n % 16
has a range of 0..15, inclusive, you are making an array of single hex digits from your number. If you would like to make an array of bytes, use 256
instead:
while(quotient != 0) {
temp = quotient % 256;
hexNum[--i] = temp;
quotient /= 256;
}
You can rewrite the same with bit shifts and bit masking:
while(quotient != 0) {
temp = quotient & 0xFF;
hexNum[--i] = temp;
quotient >>= 8;
}
To know how many bytes you need regardless of the system, use sizeof(int)
:
size_t wr_len = sizeof(int);
Upvotes: 1