C++ char 十六进制值转字节
我在字符指针中有一个十六进制值(例如“F3”),我想将其转换为字节,因为我希望将其放入数组中。我知道有很多解决方案,但它们都不是我想要的。
提前致谢!
编辑:
好吧,也许我还没有写完所有内容。 我现在拥有的:
char aChar[5];
itoa (j, aChar, 16);
j 现在是 3,我只想要它的字节数。 Atoi,scanf 没有帮助,这些是不同的解决方案。
I have a hex value in a char pointer (for example 'F3'), and I would like to convert it to byte, because I want it to put in an array. I know that there are many solutions, but they are not what I wanted.
Thanks in advance!
EDIT:
Okay, maybe I have not written everything.
What I have now:
char aChar[5];
itoa (j, aChar, 16);
j is now 3, and I just want it in byte. Atoi, scanf doesn't help, those are the different solutions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您已标记此 C++ 而不是 C,因此我不会使用任何 C 函数(除了
assert()
来演示行为、边缘条件等等等 )。这是一个示例文件。我们将其称为 hex2byte.cpp:制作它:
运行它:
无断言。添加错误处理以适应口味(例如检查何时
hex == NULL
,等等)。Since you've tagged this C++ and not C, I'm not going to use any C functions (except
assert()
to demonstrate the behaviour, edge conditions, et cetera). Here's a sample file. Let's call it hex2byte.cpp:Make it:
Run it:
No assertions. Add error handling to taste (such as checking for when
hex == NULL
, et cetera).字节通常只是一个无符号字符
或者您的意思是您有十六进制值的字符串表示形式?
A byte is usually simply an unsigned char
Or do you mean that you have a string representation of an hex value?
给定一个
char *
和"F3"
:然后你可以这样做:
我很抱歉它的丑陋;我确信它可以改进。
您可以将其变成一个函数:
Given a
char *
with"F3"
:Then you can do this:
I'm sorry for its ugliness; I'm sure it can be improved.
You can turn this into a function:
我至少可以想到五种方法:
sscanf
和%x
strtol
使用正确的基数istringstream
(尽管您必须从 unsigned Short 向下转换为 unsigned char)您列出的所有方法都不起作用。但你的问题仍然不太清楚,你有一个字符,你以某种方式使用 itoa 将其转换为十六进制,现在你想转换为字节!?!演员阵容有什么问题吗?例如
unsigned char byte = static_cast(charvalue);
I can think of at least five ways:
sscanf
with%x
strtol
with the correct baseistringstream
(though you'll have to down cast from unsigned short to unsigned char)None of the ways you listed would work. But your question still isn't really clear, you have a char which somehow you converted to hex using
itoa
and now you want to convert to a byte!?! what's wrong with a cast? e.g.unsigned char byte = static_cast<unsigned char>(charvalue);