gpt4 book ai didi

c - C语言中的fputc在遇到字符 "d5dc"时将错误的数据写入文件

转载 作者:行者123 更新时间:2023-11-30 14:46:02 26 4
gpt4 key购买 nike

i want to convert text file to binary.

for example:

"0100ed73 ed000032 0100d5dc d5dc0012"

every eight char need be converted to a int. part of my program is:

for(int i=0;i<4;i++)
{
start = tmp+i*9;
for(int j=0;j<4;j++)
{
unsigned char a = ctoi(start[0+j*2])*16+ctoi(start[1+j*2]);
fputc(a,outFilePtr);
}

}
unsigned int ctoi(char in)
{
if(in>='0'&&in<='9')
{
return in -'0';
}
else
{
return in - 'a' + 10;
}
}

at most time it is right.but after the program convert the char "d5dc",the out file no more match the in file.

提前感谢您的帮助。

最佳答案

围绕问题中显示的代码提供最小的代码集,并添加诊断打印,会生成 MCVE( Minimal, Complete, Verifiable Example ,如下所示:

#include <stdio.h>

static unsigned int ctoi(char in);

int main(void)
{
char tmp[] = "0100ed73 ed000032 0100d5dc d5dc0012";
FILE *outFilePtr = stdout;
fprintf(stderr, "Hex data: [%s]\n", tmp);

for (int i = 0; i < 4; i++)
{
char *start = tmp + i * 9;
for (int j = 0; j < 4; j++)
{
unsigned char a = ctoi(start[0 + j * 2]) * 16 + ctoi(start[1 + j * 2]);
fputc(a, outFilePtr);
fprintf(stderr, "0x%c%c = 0x%.2X = '%c'\n", start[0 + j * 2], start[1 + j * 2], a, a);
}
}
putchar('\n');
return 0;
}

static unsigned int ctoi(char in)
{
if (in >= '0' && in <= '9')
{
return in - '0';
}
else
{
return in - 'a' + 10;
}
}

并且,当通过将非打印字符转换为 \xXX 十六进制转义序列的程序运行输出时,输出为:

Hex data: [0100ed73 ed000032 0100d5dc d5dc0012]
0x01 = 0x01 = '\x01'
0x00 = 0x00 = '\x00'
0xed = 0xED = '\xED'
0x73 = 0x73 = 's'
0xed = 0xED = '\xED'
0x00 = 0x00 = '\x00'
0x00 = 0x00 = '\x00'
0x32 = 0x32 = '2'
0x01 = 0x01 = '\x01'
0x00 = 0x00 = '\x00'
0xd5 = 0xD5 = '\xD5'
0xdc = 0xDC = '\xDC'
0xd5 = 0xD5 = '\xD5'
0xdc = 0xDC = '\xDC'
0x00 = 0x00 = '\x00'
0x12 = 0x12 = '\x12'
\x01\x00\xEDs\xED\x00\x002\x01\x00\xD5\xDC\xD5\xDC\x00\x12

从表面上看,您的代码准确地生成了它应该生成的输出,因此不清楚您在哪里出现问题 - 除非它可能不直接出现在问题中显示的代码中。

关于c - C语言中的fputc在遇到字符 "d5dc"时将错误的数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52574441/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com