十进制数组转十六进制数组,不用sprintf
时间: 2023-07-17 22:07:17 浏览: 99
要将十进制数组转换为十六进制数组,可以使用以下方法,而不使用 `sprintf`:
```c
#include <stdio.h>
void decToHexArray(const unsigned char* decArray, unsigned char* hexArray, int length) {
const char hexChars[] = "0123456789ABCDEF";
for (int i = 0; i < length; i++) {
unsigned char dec = decArray[i];
unsigned char highNibble = (dec >> 4) & 0x0F;
unsigned char lowNibble = dec & 0x0F;
hexArray[i * 2] = hexChars[highNibble];
hexArray[i * 2 + 1] = hexChars[lowNibble];
}
}
int main() {
unsigned char decArray[] = {20, 30, 40, 50};
unsigned char hexArray[8];
decToHexArray(decArray, hexArray, sizeof(decArray));
printf("转换后的十六进制数组: ");
for (int i = 0; i < sizeof(hexArray); i++) {
printf("%c", hexArray[i]);
}
printf("\n");
return 0;
}
```
在上面的示例中,我们定义了一个名为 `decToHexArray` 的函数,它接受一个十进制数组和一个十六进制数组作为参数,并将十进制数组转换为对应的十六进制数组。函数内部,我们使用位运算和位掩码将每个十进制数转换为高位和低位的十六进制数。然后,根据转换后的十六进制数的值,从预定义的十六进制字符数组 `hexChars` 中获取对应的字符,并将其存储到 `hexArray` 数组中。在主函数中,我们将 `{20, 30, 40, 50}` 传递给 `decToHexArray` 函数进行转换,并打印出转换后的十六进制数组。
请注意,上述示例假设要转换的数组中的每个元素都是一个 8 位的无符号整数。如果有其他要求,请根据实际情况进行调整。
阅读全文
相关推荐


















