在C语言中将十六进制字符串转换为字节数组

68

有没有标准的C函数可以将十六进制字符串转换为字节数组
我不想自己编写函数。


1
你的意思是一个包含表示十六进制数字的字符的字符串吗? - Nate
1
是的,我有用户输入字符串,例如“abCD12ff34”,长度大于等于0,我想将其转换为字节数组,如0xaa、0xcd、0x12等。 - Szere Dyeri
22个回答

-1
这里是一个处理文件的解决方案,可能会更频繁地使用...
int convert(char *infile, char *outfile) {

char *source = NULL;
FILE *fp = fopen(infile, "r");
long bufsize;
if (fp != NULL) {
    /* Go to the end of the file. */
    if (fseek(fp, 0L, SEEK_END) == 0) {
        /* Get the size of the file. */
        bufsize = ftell(fp);
        if (bufsize == -1) { /* Error */ }

        /* Allocate our buffer to that size. */
        source = malloc(sizeof(char) * (bufsize + 1));

        /* Go back to the start of the file. */
        if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }

        /* Read the entire file into memory. */
        size_t newLen = fread(source, sizeof(char), bufsize, fp);
        if ( ferror( fp ) != 0 ) {
            fputs("Error reading file", stderr);
        } else {
            source[newLen++] = '\0'; /* Just to be safe. */
        }
    }
    fclose(fp);
}
     
int sourceLen = bufsize - 1;
int destLen = sourceLen/2;
unsigned char* dest = malloc(destLen);
short i;  
unsigned char highByte, lowByte;  
      
for (i = 0; i < sourceLen; i += 2)  
{  
        highByte = toupper(source[i]);  
        lowByte  = toupper(source[i + 1]);  
  
        if (highByte > 0x39)  
            highByte -= 0x37;  
        else  
            highByte -= 0x30;  
  
        if (lowByte > 0x39)  
            lowByte -= 0x37;  
        else  
            lowByte -= 0x30;  
  
        dest[i / 2] = (highByte << 4) | lowByte;  
}  
        

FILE *fop = fopen(outfile, "w");
if (fop == NULL) return 1;
fwrite(dest, 1, destLen, fop);
fclose(fop);
free(source);
free(dest);
return 0;
}  

-2
我知道的最好方法是:
int hex2bin_by_zibri(char *source_str, char *dest_buffer)
{
  char *line = source_str;
  char *data = line;
  int offset;
  int read_byte;
  int data_len = 0;

  while (sscanf(data, " %02x%n", &read_byte, &offset) == 1) {
    dest_buffer[data_len++] = read_byte;
    data += offset;
  }
  return data_len;
}

该函数返回保存在dest_buffer中的转换字节数。输入字符串可以包含空格和大小写字母。

"01 02 03 04 ab Cd eF garbage AB"

转换为包含以下内容的dest_buffer 01 02 03 04 ab cd ef

还有 "01020304abCdeFgarbageAB"

与之前一样进行转换。

解析在第一个“错误”处停止。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接