How integers and floating point numbers are stored in memory

integer

There are three binary representation methods for integers, namelyoriginal code, complement code and complement code

The original, inverse, and complement codes of positive integers are the same.

The three ways of representing negative integers are different.

Original code: The original code is obtained by directly translating the value into binary in the form of positive and negative numbers.

Complement code: Keep the sign bit of the original code unchanged, and invert the other bits bit by bit to get the complement code.

Complement code: the complement code + 1 will get the complement code

For shaping: the data stored in the memory actually stores the complement code.

floating point number

#include <stdio.h>
int main()
{
 int n = 9;
 float *pFloat = (float *)&n;
 printf("n的值为:%d\n",n);
 printf("*pFloat的值为:%f\n",*pFloat);
 *pFloat = 9.0;
 printf("num的值为:%d\n",n);
 printf("*pFloat的值为:%f\n",*pFloat);

In the above code, num and *pFloat are obviously the same number in the memory. Why are the interpretation results of floating point numbers and integers so different?

According to the international standard IEEE (Institute of Electrical and Electronic Engineering) 754, any binary floating point number V can be expressed in the following form:

 V = (−1) ∗ S M ∗ 2E • (−1)S represents the sign bit. When S=0, V is a positive number;

When S=1, V is a negative number • M represents a significant number,

M is greater than or equal to 1 and less than 2 • 2 E represents the exponent bit

Explanation of code

int main()// 难
{
	int n = 9;
	float* pFloat = (float*)&n;
	printf("n的值为:%d\n", n);//9
	printf("*pFloat的值为:%f\n", *pFloat);//0
	*pFloat = 9.0;
	//任意⼀个⼆进制浮点数V可以表⽰成下⾯的形式:
	//V= (−1)^S M ∗ 2^E
	// (−1)^S 表⽰符号位,当S=0,V为正数;当S=1,V为负数
	// M 表⽰有效数字,M是⼤于等于1,⼩于2的
	// 2^E 表⽰指数位
	//1001 - 9的二进制位
	// 因为是正整数 所以 S =0;
	//1.001 -M  1<=M<2
	//1.001* 2^3 =9 所以 E = 3;
	//第⼀位的符号位S=0,有效数字M等于001后⾯再加20个0,凑满23位,指数E等于3+127=130,即10000010
	//写成⼆进制形式,应该是S+E+M,即 0 10000010 001 0000 0000 0000 0000 0000
	printf("num的值为:%d\n", n);//1091567616
	printf("*pFloat的值为:%f\n", *pFloat);//9
	return 0;
}

Guess you like

Origin blog.csdn.net/dabai__a/article/details/133233370