C中的十六进制到字符数组 [英] Hex to char array in C
问题描述
给定一串十六进制值 i.e. 例如"0011223344" 所以就是 0x00, 0x11 等等.
Given a string of hex values i.e. e.g. "0011223344" so that's 0x00, 0x11 etc.
如何将这些值添加到字符数组中?
How do I add these values to a char array?
相当于说:
char array[4] = { 0x00, 0x11 ... };
推荐答案
您无法将 5 个字节的数据放入 4 个字节的数组中;这会导致缓冲区溢出.
You can't fit 5 bytes worth of data into a 4 byte array; that leads to buffer overflows.
如果字符串中有十六进制数字,则可以使用 sscanf()
和一个循环:
If you have the hex digits in a string, you can use sscanf()
and a loop:
#include <stdio.h>
#include <ctype.h>
int main()
{
const char *src = "0011223344";
char buffer[5];
char *dst = buffer;
char *end = buffer + sizeof(buffer);
unsigned int u;
while (dst < end && sscanf(src, "%2x", &u) == 1)
{
*dst++ = u;
src += 2;
}
for (dst = buffer; dst < end; dst++)
printf("%d: %c (%d, 0x%02x)\n", dst - buffer,
(isprint(*dst) ? *dst : '.'), *dst, *dst);
return(0);
}
请注意,打印以零字节开头的字符串需要小心;大多数操作在第一个空字节处终止.请注意,此代码并未空终止缓冲区;不清楚是否需要空终止,并且我声明的缓冲区中没有足够的空间来添加终端空(但这很容易修复).如果将代码打包为子程序,则很有可能需要返回转换后的字符串的长度(尽管您也可以认为它是源字符串的长度除以 2).
Note that printing the string starting with a zero-byte requires care; most operations terminate on the first null byte. Note that this code did not null-terminate the buffer; it is not clear whether null-termination is desirable, and there isn't enough space in the buffer I declared to add a terminal null (but that is readily fixed). There's a decent chance that if the code was packaged as a subroutine, it would need to return the length of the converted string (though you could also argue it is the length of the source string divided by two).
这篇关于C中的十六进制到字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!