简体   繁体   English

用C写十六进制(字节)

[英]Write Hex in C (byte)

I have to write a byte in hex to a file but I have a problem. 我必须将一个十六进制的字节写入文件,但是我遇到了问题。 For example. 例如。

If I have: 如果我有:

unsigned char a = 0x0;

and I write to a file using fwrite: 我使用fwrite写入文件:

FILE *fp = fopen("file.txt",wb);
fwrite(&a,sizeof(unsigned char),1,fp);
fclose(fp);

When I open file I always see 20h, why not 00h? 当我打开文件时,总是看到20h,为什么不显示00h?

So, I try to use: 因此,我尝试使用:

fprintf(fp,"%x",a);

In this case I see 0h, but I need a full byte, not a nibble. 在这种情况下,我看到0h,但是我需要一个完整的字节,而不是半字节。 What should I do? 我该怎么办?

The first example is hard to believe, it ought to generate a file with a single byte with the value 0 in it. 第一个示例令人难以置信,它应该生成一个包含单个字节且值为0的文件。 That's not really a text file though, so I guess your tools might fool you. 不过,这实际上不是文本文件,因此我想您的工具可能会欺骗您。

The second attempt is better, assuming you want a text file with a text representation of the value in it. 如果您想要一个文本文件,其中包含值的文本表示,则第二种尝试会更好。 To make it two hexadecimal digits, specify a width and padding: 要使其为两个十六进制数字,请指定宽度和填充:

fprintf(fp, "%02x", a);

Please note that there is no such thing as "a hex value". 请注意,没有“十六进制值”之类的东西。 A value is a value; 值就是值; it can be represented as hex, but that's not part of the value. 它可以表示为十六进制,但这不是值的一部分。 100 decimal is the same thing as 64 in hex, and 1100100 in binary. 十进制的100与十六进制的64和二进制的1100100相同。 The base only matters when representing the number as a string of digits, the number itself can't "be hex". 仅当将数字表示为一串数字时,基数才重要,数字本身不能为“十六进制”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM