C 将十六进制格式转换为十进制格式
在linux上使用gcc编译。
我想将其转换为十六进制。 10 这将是a。 我已经成功地通过下面的代码做到了这一点。
unsigned int index = 10;
char index_buff[5] = {0};
sprintf(index_buff, "0x%x", index);
data_t.un32Index = port_buff;
但是,问题是我需要将它分配给一个结构 我需要分配的元素是 unsigned int 类型。
然而,这有效:
data_t.un32index = 0xa;
但是,我的示例代码不起作用,因为它认为我正在尝试转换 从字符串到无符号整数。
我已经尝试过这个,但这也失败了
data_t.un32index = (unsigned int) *index_buff;
非常感谢您的建议,
Compiling on linux using gcc.
I would like to convert this to hex. 10 which would be a.
I have managed to do this will the code below.
unsigned int index = 10;
char index_buff[5] = {0};
sprintf(index_buff, "0x%x", index);
data_t.un32Index = port_buff;
However, the problem is that I need to assign it to a structure
and the element I need to assign to is an unsigned int type.
This works however:
data_t.un32index = 0xa;
However, my sample code doesn't work as it thinks I am trying to convert
from an string to a unsigned int.
I have tried this, but this also failed
data_t.un32index = (unsigned int) *index_buff;
Many thanks for any advice,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
啊? 如果变量中有值,则十进制/十六进制并不重要。 只需执行
十进制和十六进制只是打印数字时的表示法,以便人们可以阅读它们。
对于 C(或 C++、Java 或任何一种语言,其中这些类型是“原语”,其语义与机器寄存器的语义紧密匹配)整数变量,它所保存的值永远不能说是“十六进制” 。
该值以二进制形式(在所有典型的现代电子计算机中,本质上是数字和二进制)保存在支持变量的内存或寄存器中,然后您可以生成各种字符串表示形式,此时您需要选择一个基数来表示使用。
Huh? The decimal/hex doesn't matter if you have the value in a variable. Just do
Decimal and hex are just notation when printing numbers so humans can read them.
For a C (or C++, or Java, or any of a number of languages where these types are "primitives" with semantics closely matching those of machine registers) integer variable, the value it holds can never be said to "be in hex".
The value is held in binary (in all typical modern electronic computers, which are digital and binary in nature) in the memory or register backing the variable, and you can then generate various string representations, which is when you need to pick a base to use.
我同意前面的答案,但我想我应该分享实际上将十六进制字符串转换为无符号整数的代码,只是为了展示它是如何完成的:
执行时给出:
I agree with the previous answers, but I thought I'd share code that actually converts a hex string to an unsigned integer just to show how it's done:
Gives this when executed:
这是因为当您编写以下内容时:
您确实存在类型不匹配。 您正在尝试将字符数组
index_buff
分配给unsigned int
,即data_t.un32index
。您应该能够按照建议将
index
直接分配给data_t.un32index
。This is because when you write the following:
you do have a type mismatch. You are trying to assign a character array
index_buff
to anunsigned int
i.e.data_t.un32index
.You should be able to assign the
index
as suggested directly todata_t.un32index
.