我试图一次读取一个 64 位的输入文件,然后对这些 64 位进行一些计算,问题是我需要将 ascii 文本转换为十六进制字符。我四处搜索,但似乎没有一个答案适合我的情况。
这是我的:
int main(int argc, int * argv)
{
char buffer[9];
FILE *f;
unsigned long long test;
if(f = fopen("input2.txt", "r"))
{
while( fread(buffer, 8, 1, f) != 0) //while not EOF read 8 bytes at a time
{
buffer[8] = '\0';
test = strtoull(buffer, NULL, 16); //interpret as hex
printf("%llu\n", test);
printf("%s\n", buffer);
}
fclose(f);
}
}
对于这样的输入:
"testing string to hex conversion"
我得到这样的结果:
0
testing
0
string t
0
o hex co
0 nversion
我期望的地方:
74 65 73 74 69 6e 67 20 <- "testing" in hex
testing
73 74 72 69 6e 67 20 74 <- "string t" in hex
string t
6f 20 68 65 78 20 63 6f <- "o hex co" in hex
o hex co
6e 76 65 72 73 69 6f 6e <- "nversion" in hex
nversion
谁能看出我错在哪里?
最佳答案
strtoull 将字符串表示的数字转换为 unsigned long long。您对此函数的输入(例如字符串“testing”)毫无意义,因为它必须是数字。
printf("%llu\n", strtoull("123")); // prints 123
要得到你想要的结果,你必须像这样打印字符串的每个字符:
for(int i=0; i<8; i++)
printf( "%02X ", (unsigned char) buffer[i]);
关于C 从文件中读取 X 个字节,如果需要则填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9760593/