[英]Compare unsigned char = 0x00 and signed char = '00'
How do i compare the following: 我如何比较以下内容:
unsigned char a = 0x00;
char b = '0'; // signed char
how do i write a comparison/conversion that matches a and b? 如何编写与a和b匹配的比较/转换?
thanks! 谢谢!
'0'
and 0x00
aren't the same thing. '0'
和0x00
不是同一回事。 '0'==0x30
and '\\0'==0x00
. '0'==0x30
和'\\0'==0x00
。
Like everyone said, they are not the same thing. 就像每个人都说的那样,他们不是一回事。 But if you must compare them equal, you can do that with a lexical cast:
但是,如果必须将它们比较相等,则可以使用词法转换:
#include <iostream>
#include <boost/lexical_cast.hpp>
bool compare(unsigned char val, char c) // throws if c is not a digit!
{
return val == boost::lexical_cast<int>(c);
}
int main() {
unsigned char a = 0x00;
char b = '0';
std::cout << std::boolalpha << compare(a, b) << '\n';
}
Are you programming in C++, as your tag suggests? 您是否按照标签所示使用C ++进行编程? In that case you may prefer:
在这种情况下,您可能更喜欢:
static_cast<char>(a) == b
a == static_cast<unsigned char>(b)
Being aware, of course, of the possible loss of information in the conversion from unsigned to signed. 当然,请注意从无符号到有符号的转换中可能丢失的信息。
EDIT: Overlooked the point that others suggested. 编辑:忽略了其他人建议的观点。 Yes, 0x00 == '\\0' and 0x30 == '0'.
是的,0x00 =='\\ 0'和0x30 =='0'。 But the means for comparison still stands.
但是比较的手段仍然存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.