Issues related to char, unsigned char and literal comparison

Recently doing a project, we define a char array, which store messages sent by others. Defined message header is 0xff0xff, so after I receive the message is compared with 0xff, only to find no equal. Read some information, or find their grasp of the basics are not in place.

First of all, I wrote a test program code and operating results are as follows:

void test_num()
 {
    char a = 0x01;
    char b = 0xfe;
    unsigned char c = 0xfe;
    printf("a=%02x\n",a);
    printf("b=%02x\n",b);
    printf("c=%02x\n",c);
    printf("fe=%02x\n",0xfe);
    printf("(char)fe=%02x\n",(char)0xfe);
    printf("-1=%02x\n",-1);
    if( a == 0x01)
        cout<<"a == 0x01"<<endl;
    if( b == 0xfe)
        cout<<"b == 0xfe"<<endl;
    if( b == (char)0xfe)
        cout<<"b == (char)0xfe"<<endl;
    if( c == 0xfe)
        cout<<"c == 0xfe"<<endl;
    if( 255 == 0xff)
        cout<<"255 == 0xff"<<endl;
    if( -1 == 0xff)
        cout<<"-1 == 0xff"<<endl;
    if( -1 == 0xffffffff)
        cout<<"-1 == 0xffffffff"<<endl;
 }

Execution results are as follows:

Analysis: print 02x print is an int, and now we are passing the char type, so first of all there is type conversion. char is 8 bits, the most int 32-bit system, it is first necessary complement 24-bit data. What is that data should make it, in fact, is to look at the positive and negative circumstances of this variable, and then fill 0 positive, negative complement 1. The specific reference

https://blog.csdn.net/qq_39165336/article/details/78383239, this article conducted a detailed test.

== judgment later, while the char type, while the literals. That is what the literal constant type it? By relevant documents that literal constants are int, unsigned int, long, unsigned long, long long, unsigned long long small value. So the first few are char and int are compared, which relates to type conversion just said. Finally, a literal constant is unsigned int, char it is necessary to convert the unsigned int, an extended sign bit after understood as a positive number, in fact it is modulo. The final show that they are equal.

Finally, he says, if we want to save a string, you can define a char array, if you just want to open up a memory to save some binary data, is best defined as unsigned char.

Published 12 original articles · won praise 4 · views 20000 +

Guess you like

Origin blog.csdn.net/wuzhidefeng/article/details/82905010