如何在C中将二进制数组转换为十六进制 [英] How to convert binary array into a hexadecimal in C
问题描述
因此,目前我有一个二进制数字数组,例如{1,1,1,1,0,0,0,0},我试图弄清楚如何将这个数组转换为十六进制数字在C中键入 uint8_t(在此示例中,我希望它为0xf0),但我一直在努力寻找方法。到目前为止,我已经可以将数字转换为十六进制字符串,但我希望它是无符号整数类型。有人可以给我一些建议吗?谢谢!
So currently I have an array of binary digits, say {1, 1, 1, 1, 0, 0, 0, 0} and I'm trying to figure out how I can convert this array into a hexadecimal digit of type 'uint8_t' in C (in this example, I would want it to be 0xf0) except I'm struggling to figure out how to do so. So far I've been able to convert the digit to hexadecimal string except I want it to be an unsigned integer type. Could anyone please provide me some suggestions? Thank you!
推荐答案
尝试一下
#include <stdio.h>
#include <stdint.h>
uint16_t ConvertToDec(uint16_t* bits, uint16_t size)
{
uint16_t result = 0;
for (uint16_t i = 0; i < size; i++) {
result |= bits[i];
if(i != size-1)
result <<= 1;
}
return result;
}
int main()
{
uint16_t bits[] = { 1, 1, 1, 1, 0, 0, 0, 0 };
uint16_t len = (sizeof(bits) / sizeof(bits[0])); // get array size
uint16_t result = ConvertToDec(bits, len);
char hex[20];
sprintf(hex, "0x%02X", result);
printf("%s", hex);
return 0;
}
ConvertToDec将数组转换为8位数字,并使用sprintf将输出保存为十六进制到十六进制缓冲区中。
编辑:我对代码进行了一些修改,使其更具可读性,并且还可以使用16位数字。
ConvertToDec converts the array into 8 bit number, and using sprintf saves the output as hex into the hex buffer. Edit : I have modified the code a little bit making it more readable and also to work with 16 bit numbers as well.
最诚挚的问候
这篇关于如何在C中将二进制数组转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!