# 浮点数写，整数读

## 代码示例

#include <stdio.h>
#include <stdlib.h>

{

unsigned char *ptr = (unsigned char *)addr;
int print_bytes = 0;

if(ptr == NULL)
{
return -1;
}

for(print_bytes = 0;
print_bytes < size;
print_bytes++, ptr++)
{
#ifdef DEBUG
printf("byte %d, data = %02x -=>", print_bytes, *ptr);
#endif
for(int print_bits = 7;
print_bits >= 0;
print_bits--)
{
printf("%d", ((*ptr >> print_bits) & 1));
}
#ifdef DEBUG
printf("\n");
#endif

}
printf("\n");

return print_bytes;
}

{
int print_bytes = 0;

{
return -1;
}

while(print_bytes < size)
{
print_bytes++;
}
printf("\n");
return print_bytes;
}

int main(void)
{

printf("%d == %d\n", sizeof(float), sizeof(int));

float f = 9.0f; //对于一块内存，按浮点型初始化
int * pInt = (int *)(&f);
print_byte((void *)&f, sizeof(f));
print_bit((void *)&f, sizeof(f));

printf("the float : %f, %f\n",      f, *pInt); //以浮点视角看
printf("the int   : %d, %d, %d\n",  f, (int)f, *pInt); //以整型视角看

*pInt = 9;
print_byte((void *)&f, sizeof(f));
print_bit((void *)&f, sizeof(f));
printf("the float : %f, %f\n",      f, *pInt); //以浮点视角看
printf("the int   : %d, %d, %d\n",  f, (int)f, *pInt); //以整型视角看

return EXIT_SUCCESS;
}

float 9.0表示出来 =1001×20=1.001×23$1001 × 2^{0} = 1.001 × 2^{3}$

0 10000010 00100000000000000000000

## 浮点数读

### 第二种读取方式:用pInt型指针按照浮点数格式读取

V=(-1)^0×0.00000000000000000001001×2^(-126)=1.001×2^(-146)

## 整数读

### 第一种方式，直接printf以”%d”输出浮点数f

printf("%d", f) <-==->printf("%d", 9.0f);

• 求出它的单精度内存表示，
• 转换为双精度，有效位不足补0，
• 输出低32位所表示的十进制数
总的来说，在打印一个浮点数时，一.浮点数转换成双精度 二. 打印低32位.

### 第三种读取方式:用一个int型的指针去读取

0 10000110 0110010001000000000

# 整数写，浮点数读

int main(void)
{
printf("%d == %d\n", sizeof(float), sizeof(int));

int num = 9;                                /* num是整型变量，设为9 */
float* pFloat = (float *)&num;              /* pFloat表示num的内存地址，但是设为浮点数 */

print_byte((void *)&num, sizeof(num));
print_bit((void *)&num, sizeof(num));

printf("the float : %f, %f\n",       num, *pFloat); //以浮点视角看
printf("the int   : %d, %d\n",  (int)num, *pFloat); //以整型视角看

*pFloat = 9.0f;                                /* 将num的值改为浮点数 */
print_byte((void *)&num, sizeof(num));
print_bit((void *)&num, sizeof(num));

printf("the float : %f, %f\n",       num, *pFloat); //以浮点视角看
printf("the int   : %d, %d\n",  (int)num, *pFloat); //以整型视角看

return EXIT_SUCCESS;
}