IEEE标准754浮点数转换【代码篇】

本文介绍了如何使用C语言的Union和位字段概念来实现32位单精度IEEE 754浮点数的转换。通过两个程序分别展示了将实数转换为浮点表示,以及将浮点表示还原回实数的过程。
摘要由CSDN通过智能技术生成

目录

编写一个程序,找出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 :
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值