如何在C程序中的unsigned char变量中打包hex值?
我在一个字符串中有一个hex值"F69CF355B6231FDBD91EB1E22B61EA1F"
,我在我的程序中使用这个值,通过硬编码unsigned char变量中的值,如下所示: unsigned char a[] = { 0xF6 ,0x9C ,0xF3 ,0x55 ,0xB6 ,0x23 ,0x1F ,0xDB ,0xD9 ,0x1E ,0xB1 ,0xE2 ,0x2B ,0x61 ,0xEA ,0x1F};
是否有任何函数或任何其他方法可以从字符串中获取值并通过打包将其放入hex格式的无符号变量中?
#include #include int hctoi(const char h){ if(isdigit(h)) return h - '0'; else return toupper(h) - 'A' + 10; } int main(void){ const char cdata[]="F69CF355B6231FDBD91EB1E22B61EA1F"; unsigned char udata[(sizeof(cdata)-1)/2]; const char *p; unsigned char *up; for(p=cdata,up=udata;*p;p+=2,++up){ *up = hctoi(p[0])*16 + hctoi(p[1]); } { //check code int i; for(i=0;i
您可以使用sscanf
将字符串中的hex值转换为值。 如果你想要一个值数组,那么你可以编写一个函数将输入字符串分成两个字符段,并使用sscanf
转换每个字符串。 (我没有永远做过C,所以我不知道这是不是一个很好的方法。)
如果只有32个单hex值(16字节,128位),那么您可以查看libuuid
提供的方法。
libuuid
是e2fsprogs
包的一部分。 无论如何,一些Linux发行版,例如Debian,将libuuid
作为一个单独的包发布 。 要使用Debian软件包进行开发,您还需要查看此处 。
使用sscanf()
在c ++中检查这个问题 。
对于c ,它将是这样的:
char *str = "F69CF355B6231FDBD91EB1E22B61EA1F"; char substr[3] = "__"; unsigned char *a = NULL; len = strlen(str); a = malloc(sizeof(unsigned char)*(len/2)+1); for ( i = 0; i < len/2; i++) { substr[0] = str[i*2]; substr[1] = str[i*2 + 1]; sscanf( substr, "%hx", &a[i] ); } free(a);
引入辅助函数data_length
和data_get
以轻松迭代数据。 以下程序在stdout
上转储解压缩的unsigned chars,每行一个:
#include #include #include #include /* htoi(H) Return the value associated to the hexadecimal digit H. */ int htoi(char h) { int a = -1; if(isdigit(h)) { a = h - '0'; } else { a = toupper(h) - 'A' + 10; } return a; } /* data_length(D) The length of the data stored at D. */ int data_length(const char* d) { return strlen(d) / 2; } /* data_get(D, K) Return the K-th unsigned char located encoded in d. */ unsigned char data_get(const char *d, int k) { return htoi(d[2*k]) * 0x10 + htoi((d+1)[2*k]); } int main() { const char cdata[]="F69CF355B6231FDBD91EB1E22B61EA1F"; for(int i = 0; i < data_length(cdata); ++i) { printf("0x%02hhx\n", data_get(cdata, i)); } return EXIT_SUCCESS; }