将 int 转换为 uint8_t 数组十六进制值
Converting an int to uint8_t array HEX value
我想要一个整数,并将其转换为 uint8_t 十六进制数数组?转换后的 int 在 HEX 中的长度最大为 8 个字节。我能够使用一种方法将 int (19604) 转换为 uint8_t 数组,如下所示:
00-00-00-00-00-00-00-00-04-0C-09-04
但我需要它看起来像这样:
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;
}
我该怎么做呢?我应该使用不同的算法还是应该尝试对结果进行位移?我对 C 中的位移有点陌生,所以一些帮助会很棒。谢谢!
由于 n % 16
的范围是 0..15(含),因此您正在根据您的号码制作一个十六进制数字数组。如果您想创建一个字节数组,请改用 256
:
while(quotient != 0) {
temp = quotient % 256;
hexNum[--i] = temp;
quotient /= 256;
}
您可以使用移位和位掩码重写:
while(quotient != 0) {
temp = quotient & 0xFF;
hexNum[--i] = temp;
quotient >>= 8;
}
无论系统如何,要知道您需要多少字节,请使用 sizeof(int)
:
size_t wr_len = sizeof(int);
考虑以下代码:
#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;
}
只用一个简单的语句就可以将int转换成byte buffer
memcpy((char*)hexBuffer,(char*)&n,sizeof(int));
打印循环时可以使用 8 而不是 4
为此使用联合
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');
我想要一个整数,并将其转换为 uint8_t 十六进制数数组?转换后的 int 在 HEX 中的长度最大为 8 个字节。我能够使用一种方法将 int (19604) 转换为 uint8_t 数组,如下所示:
00-00-00-00-00-00-00-00-04-0C-09-04
但我需要它看起来像这样:
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;
}
我该怎么做呢?我应该使用不同的算法还是应该尝试对结果进行位移?我对 C 中的位移有点陌生,所以一些帮助会很棒。谢谢!
由于 n % 16
的范围是 0..15(含),因此您正在根据您的号码制作一个十六进制数字数组。如果您想创建一个字节数组,请改用 256
:
while(quotient != 0) {
temp = quotient % 256;
hexNum[--i] = temp;
quotient /= 256;
}
您可以使用移位和位掩码重写:
while(quotient != 0) {
temp = quotient & 0xFF;
hexNum[--i] = temp;
quotient >>= 8;
}
无论系统如何,要知道您需要多少字节,请使用 sizeof(int)
:
size_t wr_len = sizeof(int);
考虑以下代码:
#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;
}
只用一个简单的语句就可以将int转换成byte buffer
memcpy((char*)hexBuffer,(char*)&n,sizeof(int));
打印循环时可以使用 8 而不是 4
为此使用联合
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');