本文介绍了scanf 十六进制长字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式如下的文件:

I have a file with the following format:

0 b71b3a8de0c18abd2e56ec5f4efc4af2ba084604
1 4bec20891a68887eef982e9cda5d02ca8e6d4f57

第一个值是一个整数,第二个整数是一个 20 字节的十六进制编码值.我希望能够使用 fscanf 循环读取这两个值,如下所示:

The first value is an integer, and the second integer is a 20-byte value encoded in hexadecimal. I want to be able read in both values using a fscanf loop like so:

FILE *file = fopen("file.txt", "r");
int id;
char hash[20];
while(fscanf(has_chunks, "%i %40x\n", &id, c_hash) == 2){
   // Do Stuff
}

然而,这显然行不通,因为 %40x 需要一个 unsigned int 指针,但这不足以容纳该值.我知道我可以做多个格式化程序,比如 %x%x%x,但这看起来并不优雅.有没有更好的方法可以使用 fscanf 做到这一点?

However, this clearly doesn't work, as %40x expects an unsigned int pointer, but this is not large enough to hold the value. I know I can do multiple formatters, like %x%x%x, but this doesn't seem elegant. Is there a better way I can do this using fscanf?

推荐答案

b7 1b 3a 8d e0 c1 8a bd 2e 56 ec 5f 4e fc 4a f2 ba 08 46 04

每对字符的范围在00xff之间.这适合一个字节,或 unsigned char.哈希函数通常也需要 unsigned char.

Each pair of characters is in the range between 0 to 0xff. This fits in one byte, or unsigned char. Hash functions normally expect unsigned char as well.

使用以下转换:

int i, id;
unsigned int v;
unsigned char hash[20];
char buf[41];
while(fscanf(file, "%d %s\n", &id, buf) == 2)
{
    for(i = 0; i < 20; i++)
    {
        if(sscanf(buf + i * 2, "%2x", &v) != 1) break;
        hash[i] = (unsigned char)v;
    }
}

这篇关于scanf 十六进制长字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 18:19