1, when signed less bytes assigned to multi-byte signed, placing low byte, high-byte complement sign bit.
2, unsigned char assigned to integer variables, placing the lower byte, the upper byte of 0s;
3, when the symbol character assigned to integer variables, placing low byte, high-byte complement the sign bit.
4, a conversion is to be understood that a binary-based, then the sign bit is determined according to the type of original. General problem does not occur in the range beyond the range error will occur.
One,
#include <iostream>
int main(){
// 将右边的数字转换为二进制再赋予
unsigned char a1 = -1;
signed char a2 = -1;
// 类型自动转换
std::cout<<(int)a1<<" "<<(int)a2<<std::endl;
if(a1 == a2){
std::cout<<"ok";
}
return 1;
}
It will be converted into -1 11111111 complement form, then the conversion time of the signed int type, for unsigned char, high bit 0; signed char the high bit of the sign bit. When printing in accordance with the signed int type print
output:
255 -1
--------------------------------
two,
#include <iostream>
int main(){
unsigned char a1 = 128;
// 数值溢出
signed char a2 = 128;
std::cout<<(int)a1<<" "<<(int)a2<<std::endl;
if(a1 == a2){
std::cout<<"ok";
}
return 1;
}
128 within the range of an unsigned char, no problem. But beyond 128 signed char type, binary 10000000, assigned to this time a signed int, upper extended sign bit, becomes -128.
Output:
128 -128
--------------------------------
three,
#include <iostream>
int main(){
unsigned char a1 = 256;
signed char a2 = 256;
std::cout<<(int)a1<<" "<<(int)a2<<std::endl;
if(a1 == a2){
std::cout<<"ok";
}
return 1;
}
Output:
0 0
ok
--------------------------------