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/conversi开发者_如何学编程on that matches a and b?
thanks!
'0'
and 0x00
aren't the same thing. '0'==0x30
and '\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? 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'. But the means for comparison still stands.
精彩评论