比较保存十六进制值的 Char C++
在 C++ 中,我有两个保存十六进制值的字符,例如:
char t = 0x4;
char q = 0x4;
如果字符中保存的两个值相同,我将如何比较? 我试过了
if (t == q) // should give me true
,但是不行,请帮忙,谢谢!
in C++ I have two chars holding hex values e.g.:
char t = 0x4;
char q = 0x4;
How would i compare if the two values held in the char are the same?? I tried
if (t == q) // should give me true
but no, any help, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
char 只是一个 8 位整数。 使用十六进制或十进制文字初始化它并不重要,无论哪种情况,之后 char 的值都是相同的。
所以:
它相当于:
你提到上面不是真的,但是你的代码一定有错误或者t和q一定不一样。
您的建议...
不正确。 为什么
? q 进行按位比较,返回两个对齐位均为 1 的值
。只要 t 和 q 的任何位相同,术语“if(t&q)”就会返回 true。
因此,如果 t = 3 (二进制 00000011)和 q = 1 (二进制 00000001)那么 (t&q) 将返回 true,即使知道它们不相等。
A char is just an 8-bit integer. It doesn't matter if you initialized it with hex or decimal literal, in either case the value of the char will be the same afterwards.
So:
It is equivalent to:
You mentioned that the above is not true, but you must have an error in your code or t and q must not be the same.
What you suggested...
is not correct. Why?
t & q does a bitwise compare, returning a value where both aligned bits are 1.
The term "if(t&q)" would return true as long as any of the bits of t and q are in common.
so if t = 3 which is in binary 00000011 and q = 1 which is in binary 00000001 then (t&q) would return true even know they are not equal.
啊,我找到了解决方案:
Ah, I found the solution: