Conversion of common data types in C/C++

C++ data types can also be ranked by rank. If a numeric data type can hold more numbers than another data type, it is ranked higher than the latter. For example, the float type surpasses the int type, and the double type surpasses the float type. The following table lists the data types in order from highest to lowest.

long double

double

float

unsigned long long int

long long int

unsigned long int

long int

unsigned int

int

An exception to ranking in tables is when int and long int are the same size. In this case, unsigned int will outperform long int because it can hold higher values.

  • Integer to floating point

  • The fractional part is recorded as 0, and the integer part is reserved, but there may be a loss of precision. (For example: floating-point numbers are expressed in the form of exponents in the machine, decomposed into four parts: number symbol, mantissa, exponent symbol, and exponent to record the most significant digit. When the effective digit of the integer exceeds the mantissa of the floating-point number, it may be A part of the precision is discarded)

  • Float to Integer

  • The decimal part is discarded, and the integer part is reserved. But overflow occurs when the integer part is larger than the range of int.

  • signed to unsigned

  • There is no difference between the two in terms of binary representation. But the highest bit of signed and unsigned numbers is different, so the negative number is converted to unsigned = 2^32 - the absolute value of the negative number

  • unsigned to signed

  • Similarly, there is no difference between the two in terms of binary representation. Overflow when the highest bit is 1, become a negative number, = - (uint - 2^31)

  • conversion between integers

  • Signed number, the sign bit remains unchanged, the high bit is trimmed, and the high bit is missing.

  • Unsigned number, more high-order clipping, less high-order zero padding

  • Conversion between floating point numbers

  • Float to double, neither overflow nor loss of precision

  • Converting double to float may overflow or lose precision

For the conversion between signed and unsigned numbers of different sizes, first convert the size according to the rules, and then convert the symbols according to the rules.

Summary: The conversion of different digits adopts zero padding and discarding methods. The conversion of signed and unsigned is essentially a conversion of binary invariance. The conversion of integer and floating point is a conversion of discarding decimals and retaining integer bits.

Guess you like

Origin blog.csdn.net/qq_55796594/article/details/129320928