C中十六进制字符串到int的转换
我有一个包含十六进制值的文本文件,在 fscanf 一个值之后,我需要知道如何将其从十六进制字符串转换为 int。然后将其转换回十六进制字符串以供以后打印。有人知道这方面的算法吗?谢谢。
I have a text file with hexadecimal values, after I fscanf a value I need to know how I can convert it from hexadecimal string to an int. And then convert it back to hexadecimal string for a later print. Anyone knows an algorithm for this? thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用
%x
格式说明符而不是%s
来读取您的值。这会将数据读取为十六进制整数。例如,如果您的文件如下所示:
然后你可以像这样读取这3个值:
You should use the
%x
format specifier instead of%s
to read your values. This will read the data as hexadecimal integers.For example, if your file looks like this:
Then you can read those 3 values like this:
在
fscanf
和fprintf
字符串中使用%x
格式说明符。Use the
%x
format specifier in yourfscanf
andfprintf
strings.正如 Marlon 上面所说:
要以十六进制字符串打印,
我认为您可能会对计算机存储 int 类型变量的方式感到困惑。它们不是以 10 为基数存储的。它们是以二进制存储的,我相信您知道。这意味着将十六进制值分配给 int 没有什么特别的。它不会以任何不同的方式存储。使用
%x
只是表明您希望程序理解您给它的数字是十六进制数字(例如,它知道将字符串“10”存储为 10000(2) 而不是与 1010(2) 相同。如果您的变量a
具有二进制 10000(2) 并且您使用%x
打印它,则程序知道输出应该是10
。如果您使用%d
,它知道输出应该是16
。As Marlon said above:
To print back as hex strings
I think that you might be confused about the way the computer stores variables of type
int
. They are not stored in base 10. They are stored in binary, as I'm sure you know. That means that there is nothing special about assigning a hex value to anint
. It won't be stored any differently. Using the%x
just shows that you want the program to understand that the number you are giving it is a hex number (for example so it knows to store the string "10" as 10000(2) rather than as 1010(2). Same thing with output. If your variablea
has the binary 10000(2) and you print it using%x
, the program knows that the output should be10
. If you use%d
, it knows that the output should be16
.