简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM