[Embedded C] Forced type conversion

Type conversion:
  Low to high: continuation, highest bit filling;
  High to low: truncation
  Using direct cast does not remove the symbol.

Type conversion between variables of equal length

When different types of the same length are converted to each other, for example, shortshort is forced to unsigned shortunsigned short. In fact, during the conversion process, the converted unsigned shortunsigned short is the same as the binary representation of the original shortshort in the computer. What changes is just the way they are interpreted.

The result of the cast leaves the bit values ​​unchanged and just changes the way the bits are interpreted.

short a = -4321;
unsigned short ua = (unsigned short)a;  //  这里进行强制类型转换 ua的真值是61215

Type conversion between variables of different lengths

Conversion of long word length variable to short word length variable

The system directly truncates the excess high-order word length and directly assigns the low-order part.

u16 exmple = 1000 0000 1111 0000;
u8 res;
res = (u8)exmple;
//res的值就是1111 0000

When converting a short word length variable to a long word length variable, the high-order part will also be expanded to原数字的符号位

When the short word length turns to the long word length, not only the corresponding bit values ​​are equal, but the high-order part will also be expanded into the sign bit of the original number;

Handling negative numbers

Binary problem about negative numbers: We use negative numbers补码,原码 to take the inverse transformation反码, and add the complement 1 becomes two’s complement.

For example, 1 is 0000 0001
The original code of -1: 1000 0001
The reverse code: 1111 1110
Complement code: 1111 1111
and when -1 is used, it is 1111 1111

Then if -1 of char type is forced to unsigned char, the result is 1111 1111 is interpreted as 255.

The result of the cast leaves the bit values ​​unchanged and just changes the way the bits are interpreted.

Then if the -1 of the char type is forced to be converted into an unsigned unsigned short, the result is 1111 1111 1111 1111, which is interpreted as 65535.

The high-order part will also be expanded to the sign bit of the original number!

Direct use of cast does not remove the symbols

The int32 type is used in the code to assign the decimal value 2147483648 (0x8000 0000) to the uint64 type. In the binary of the int32 type, the highest bit is 1, which is expressed as a complement. In the process of assigning value from Int32 to uint64 type, there are two processes: ① upgrade int32 to int64, at this time all the extra highest bits are filled with 1, and it becomes 0xffffffff80000000; ②, convert int64 to uint64, at this time The decimal value is 18446744071562067968. So the value is much larger than 2147483648.

Guess you like

Origin blog.csdn.net/apythonlearner/article/details/133876041