目录
编写一个程序,找出32位单精度IEEE 754浮点表示的给定实数,反之亦然。
示例:
Input: real number = 16.75
Output: 0 | 10000011 | 00001100000000000000000
Input: floating point number = 0 | 10000011 | 00001100000000000000000
Output: 16.75
方法:
该实现基于C语言中的Union数据类型,并使用了位字段的概念。
当我们不需要通常分配给某些变量的全部内存,但希望限制这些变量占用的内存数量时,就会分配位字段。在C语言中,Union的成员共享公共内存空间,每次只能访问一个成员。
以下是上述方法的实施情况:
程序1:将实值转换为它的浮点表示形式
// C program to convert a real value
// to IEEE 754 floating point representaion
#include <stdio.h>
void printBinary(int n, int i)
{
// Prints the binary representation
// of a number n up to i-bits.
int k;
for (k = i - 1; k >= 0; k--) {
if ((n >> k) & 1)
printf("1");
else
printf("0");
}
}
typedef union {
float f;
struct
{
// Order is important.
// Here the members of the union data structure
// use the same memory (32 bits).
// The ordering is taken
// from the LSB to the MSB.
unsigned int mantissa :