gpt4 book ai didi

c - 为什么八进制转储输出整数变量的ascii码而不是二进制码?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:20 24 4
gpt4 key购买 nike

这是用 C 编写的代码,用于将字符和整数变量输入到文件中。

int main(void)
{
FILE *fp;
char file[20];
int i = 40;

printf("Enter filename: ");
scanf("%s", file);

fp = fopen(file, "wb");

fprintf(fp, "%d", i);
fprintf(fp, "%c%c", '4', '0');

fclose(fp);

return 0;
}

假设文件名为文本并且调用了 od 命令..

od -xc text

这是命令的输出

0000000    3034    3034
4 0 4 0

为什么它打印值 40 的 ASCII 值而不是整数变量的十六进制代码 0028?

最佳答案

fprintf 将所有输出格式化为文本 - fprintf( fp, "%d", 42 ) 写入字符值 ' 4''2' 到输出流,与 fprintf( fp, "%c%c", '4', '2' )fprintf( fp, "%s", "42")

如果要将整数的二进制表示形式写入输出流,则需要使用 fwrite( &i, sizeof i, 1, fp );

关于c - 为什么八进制转储输出整数变量的ascii码而不是二进制码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37840289/

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