十六进制字符数组用C [英] Hex to char array in C
问题描述
由于十六进制值即例如串0011223344所以这是为0x00,为0x11等。
我如何将这些值添加到一个字符数组?
等同于说:
字符数组[4] = {0×00,0×11 ...};
您可以不适合5个字节的有价值的数据到一个4字节数组;导致缓冲区溢出。
如果您有十六进制数字的字符串,可以使用的sscanf()
和循环:
的#include<&stdio.h中GT;
#包括LT&;&文件ctype.h GT;诠释的main()
{
为const char * SRC =0011223344;
炭缓冲液[5];
字符* DST =缓冲;
字符*结束=缓冲+的sizeof(缓冲区);
unsigned int类型U; 而(DST<&到底放;&安培; sscanf的(SRC,%2X,&安培; U)== 1)
{
* DST ++ = U;
SRC + = 2;
} 对于(DST =缓冲; DST< END; DST ++)
的printf(%d个:%C(%D,为0x%02X)\\ n,DST - 缓冲,
(?isprint判断(* DST)* DST:'。'),* DST,* DST); 返回(0);
}
请注意在打印开始与一个零字节串需要小心;大多数操作上的第一个空字节终止。请注意,这code没空终止缓冲区;目前尚不清楚空终止是否是理想的,并没有在我声明添加一个终端空缓冲器有足够的空间(但很容易固定)。有一个像样的机会,如果code被打包成一个子程序,就需要返回转换后的字符串的长度(虽然你也可以认为它是源字符串除以二的长度)。
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?
Equivalent to say:
char array[4] = { 0x00, 0x11 ... };
You can't fit 5 bytes worth of data into a 4 byte array; that leads to buffer overflows.
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);
}
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屋!