当前位置:网站首页>Negative number storage and type conversion in programs

Negative number storage and type conversion in programs

2022-07-05 07:08:00 An embedded enthusiast

How negative numbers are stored in computers

What is the original code 、 Inverse code 、 Complement code

It is divided into : Positive numbers And negative numbers ( Include positive floating point numbers , And negative floating point numbers ). Specify that the highest bit sign bit positive number is 0, A negative number is 1( The reasons are explained below )

Original code :
10 Base to zero 2 Hexadecimal is the original code , But the original code of a positive number is itself, and the sign bit is 0, The sign bit of the original code of a negative number is 1( The following pages take single byte as an example :10 Base number 1 The original code is 0000 0001,10 Base number -1 The original code is 1000 0001).
Inverse code :
The inverse of a positive number is itself , The inverse code of a negative number is the original code of a negative number 0 Turn into 1,1 Turn into 0 (-1 The original code is 1000 0001 The inverse of it is 1111 1110,).( Note that the sign bits of negative numbers do not participate in the transformation ).
Complement code :
The complement of a positive number is itself , The complement of a negative number is the inverse of a negative number plus one (-1 The original code is 1000 0001 The inverse of it is 1111 1110 Its complement is 1111 1111).
summary :
The original code of a positive number , Inverse code , Complement three values in one , The original code of negative number , Inverse code , The complement is different .

Why set the inverse code , Complement code

Some people will wonder why we should use inverse code , Complement code , Don't use the original code directly ? First make it clear that the inverse complement original code is for binary numbers , If the computer adds and subtracts with the original code , Positive numbers plus positive numbers don't make mistakes , However, the addition of positive and negative numbers will make mistakes .
 Insert picture description here
The purpose of introducing complement code is to make subtraction more convenient for computer . To put it bluntly , Complement and inverse code are designed to simplify subtraction , Change the minus sign to a negative number , Then turn negative numbers into complements for addition , It has nothing to do with positive numbers , Whether it's a positive integer or a positive decimal , Original code 、 Inverse code 、 The complements are all the same .

It turns out that negative numbers in computers are stored in complement , It can also be extended to , All numbers in the computer are stored in the form of complement .

Analyze the essence

1、 The storage range of a single byte unsigned positive number is 0 ~ 255 Binary representation ( 0000 0000~1111 1111)
2、 The storage range of single byte integer with negative sign is -128 ~127 .
Let's first look at the range that positive binary can represent (0000 0001 ~ 0111 1111) namely 1~127
The range that negative binary numbers can represent (1000 0001 ~ 1111 1111) namely -127~-1
So there's another 0 It is divided into +0 and -0 (0000 0000 Express +0,1000 0000 Express -0 Express -128)

C Language data type conversion ( Automatic type conversion + Cast )

Automatic type conversion

Automatic type conversion is when the compiler silently 、 Implicitly 、 Data type conversion secretly , This transformation does not require programmer intervention , It happens automatically .

1、 Automatic type conversion occurs when one type of data is assigned to another type of variable , for example :

float f = 100;

100 yes int Data of type , It needs to be converted to float Type can be assigned to a variable f. Again :

int n = f;

f yes float Data of type , It needs to be converted to int Type can be assigned to a variable n.

In assignment operations , The data types on both sides of the assignment number are different , You need to convert the type of the expression on the right to the type of the variable on the left , This may cause data distortion , Or the accuracy is reduced ; So , Automatic type conversion is not necessarily safe . For unsafe type conversions , Compilers usually give warnings .

2、 In different types of mixed operations , The compiler also automatically converts data types , Convert all data involved in the operation to the same type first , And then calculate . The rules of transformation are as follows :

  • The conversion proceeds in the direction of increasing data length , To ensure that the value is not distorted , Or the accuracy is not reduced . for example ,int and long When participating in the operation , The first int Type of data into long Type and then calculate .
  • All floating-point operations are performed with double precision , Even if there is only float type , Also convert to double type , In order to do the calculation .
  • char and short When participating in the operation , It must be converted to int type .

The following figure describes this transformation rule more vividly :
 Insert picture description here
unsigned That is to say unsigned int, You can omit int, Just write unsigned.

Cast

Automatic type conversion is the result of the compiler's own judgment according to the context of the code , Sometimes it's not so “ intelligence ”, Can't meet all the needs . if necessary , Programmers can also explicitly propose type conversion in their own code , This is called cast .

Automatic type conversion is the compiler silently 、 An implicit type conversion , It doesn't need to be reflected in the code ; Mandatory type conversion is explicitly proposed by programmers 、 A type conversion that needs to be specified by code in a specific format . let me put it another way , Automatic type conversion requires no programmer intervention , Casts must have programmer intervention . The format of the cast is :

(type_name) expression
//type_name Name the new type ,expression Expression for . for example :
(float) a;  // Put the variable  a  Convert to  float  type 
(int)(x+y);  // Put the expression  x+y  The result of is converted to  int  integer 
(float) 100;  // Numerical value  100( The default is int type ) Convert to  float  type 

The following is a classic example that requires cast :

#include <stdio.h>
int main(){
    
    int sum = 103;  // total 
    int count = 7;  // number 
    double average;  // The average 
    average = (double) sum / count;
    printf("Average is %lf!\n", average);
    return 0;
}

Running results :
Average is 14.714286!

sum and count All are int type , Without intervention , that sum / count The result of the operation is also int type , The decimal part will be discarded ; Although it is average yes double type , Can receive decimal parts , But the heart has spare power and insufficient strength , The decimal part is written in advance “ castration ” 了 , It can only receive integer parts , This leads to serious distortion of the result of division operation .

since average yes double type , Why not make full use of , Try to improve the accuracy of the calculation results ? To achieve this goal , We just need to sum perhaps count One of them is converted to double The type is enough . In the above code , We will sum Cast to double type , such sum / count The result will also become double type , You can keep the decimal part ,average The received value will also be more accurate .

In this code , There are two points to note :

  • For division operations , If both divisor and dividend are integers , Then the result of the operation is also an integer , The decimal part will be discarded directly ; If one of the divisor and the divisor is a decimal , So it's also going to be a decimal . This has been in 《C Language addition, subtraction, multiplication and division 》 It is explained in detail in .
  • ( ) Has a higher priority than /, For the expression (double) sum / count, Will execute first (double) sum, take sum Convert to double type , And then we do Division , So the result is double type , Able to retain decimal parts . Be careful not to write (double) (sum / count), The result of this operation will be 3.000000, Still can't keep the decimal part .

Type conversion is only temporary

Whether it's automatic type conversion or forced type conversion , It's just a temporary conversion for this operation , The result of the conversion will also be saved to the temporary memory space , It will not change the original type or value of data . Please see the following example :

#include <stdio.h>
int main(){
    
    double total = 400.8;  // The total price 
    int count = 5;  // number 
    double unit;  // The unit price 
    int total_int = (int)total;
    unit = total / count;
    printf("total=%lf, total_int=%d, unit=%lf\n", total, total_int, unit);
    return 0;
}

Running results :
total=400.800000, total_int=400, unit=80.160000

Pay attention to the first place. 6 Line code ,total The variable is converted to int Type is assigned to total_int Variable , And this transformation does not affect total The type and value of the variable itself . If total The value of has changed , that total The output of will become 400.000000; If total The type of has changed , that unit The output of will become 80.000000.

Automatic type conversion VS Cast

stay C In language , Some types can be converted automatically , You can also cast , for example int To double,float To int etc. ; Some types can only be cast , Can't switch automatically , For example, what will be learned later void * To int *,int To char * etc. .

Types that can be automatically converted must be cast , however , Types that need to be cast may not be automatically cast . Now we've learned about data types , It can automatically convert , It can also be forced to convert , In the future, we will also learn some types that can only be cast but not automatically cast .

Automatic type conversions are generally less risky , There will be no serious consequences for the program , for example ,int To double No shortcomings ,float To int At best, it's numerical distortion . Type conversions that can only be forced are generally risky , Or act strangely , for example ,char * To int * It's a strange transformation , This leads to strange values , Again ,int To char * It's a very risky conversion , It usually causes the program to crash .

When using cast , Programmers themselves should be aware of the potential risks .

Last

Recommended reading :C Language course

原网站

版权声明
本文为[An embedded enthusiast]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050636022389.html