在C中写入十六进制(字节) [英] Write Hex in C (byte)

查看:196
本文介绍了在C中写入十六进制(字节)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个十六进制的字节到一个文件,但我有一个问题。例如。

如果我有:

  unsigned char a =为0x0; 

我使用fwrite写入一个文件:

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

当我打开文件时,我总是看到20h,为什么不是00h?



因此,我尝试使用:

  fprintf(fp,%x,a); 

在这种情况下,我会看到0h,但我需要一个完整的字节,而不是一个半字节。
我应该怎么做?

解决方案

第一个例子很难相信,它应该生成一个带有单个字节,其值为0。这不是一个真正的文本文件,所以我猜你的工具可能会欺骗你。

第二次尝试更好,假设你想要一个带有文本文本表示的文本文件它的价值。要创建两个十六进制数字,请指定宽度和填充:

  fprintf(fp,%02x,a); 

请注意,没有十六进制值这样的东西。值是一个值;它可以被表示为十六进制,但这不是该值的一部分。 100十进制与十六进制中的64相同,1100100二进制。基数只在将数字表示为一串数字时很重要,数字本身不能为十六进制。


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?

解决方案

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".

这篇关于在C中写入十六进制(字节)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆