Write Hex in C (byte)

£可爱£侵袭症+ 提交于 2019-12-13 05:14:17

问题


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:

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?

So, I try to use:

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

In this case I see 0h, but I need a full byte, not a nibble. What should I do?


回答1:


The first example is hard to believe, it ought to generate a file with a single byte with the value 0 in it. 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. The base only matters when representing the number as a string of digits, the number itself can't "be hex".



来源:https://stackoverflow.com/questions/21682441/write-hex-in-c-byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!