在 C 中将 float 转换为 IEEE 格式

标签 c binary ieee-754 ieee

我需要将 float 转换为 IEEE( float 由 scanf 给出,它必须来自 scanf,否则它会丢失并出错),但我似乎无法让它工作。我尝试使用 argc 和 argv,它是正确的,但我的提交平台不接受它,因为我需要通过扫描获取 float 。问题是因为我尝试使用扫描,它不会打印正确的位。

数字 10 的输出应该是:

位:01000001001000000000000000000000

信号:+

指数:3

尾数:1.25000000

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

typedef unsigned char Byte;

int expoente;
char sinal;
float mant=1;
int vector[32];
int vectorCounter=0;
char number;


void escreve_IEEE(char sinal, int expoente, float mant) 
{ 
  printf ("sinal: %c\n", sinal);
  printf ("expoente: %d\n", expoente);
  printf ("mantissa: %.8f\n", mant);
}

int expoenteBaseDois(int exp) 
{
  int result = 1;
  int i = 0;
  while (i < exp) {
    result = 2 * result;
    i++;
  }
  return result;
}

void conversion(Byte b[]) {
  int i = 3;
  int v;
  int s;
  while ( i >= 0) {
    v = b[i];
    s = 7;
    while (s >= 0) {
      vector[vectorCounter] = (v >> s) & 1;
      vectorCounter++;
      s--;
    }
    i--;
  }
  vectorCounter = 0;
  if(vector[vectorCounter]==0) sinal='+';
  else sinal='-';
  vectorCounter++;
  int exp = -127;
  s = 7;
  while (vectorCounter <= 8) {
    exp = exp + vector[vectorCounter] * expoenteBaseDois(s);
    s--;
    vectorCounter++;
  }
  expoente = exp;
  s = 1;
  while (vectorCounter <= 31) {
    mant = mant + vector[vectorCounter] * ( 1.0 / (expoenteBaseDois(s)));
    s++;
    vectorCounter++;
  }

}

int main(int argc, char *argv[]) {
  float num;
  scanf("%f", &num);
  number= *(char*)&num;
  conversion((Byte *) &number);
  vectorCounter=0;
  printf("bits: ");
  while(vectorCounter>=0 && vectorCounter<32)
  {
    printf("%d",vector[vectorCounter]);
    vectorCounter++;
  }
  printf("\n");
  escreve_IEEE(sinal, expoente, mant);
  return 0;
}

最佳答案

您可以通过修改 main 的第一条指令来修复奇怪的代码:

    float num;
    scanf("%f", &num);
//  number= *(char*)&num;
    conversion((Byte *) &num);

在您的代码中,您将全局 char 变量传递给需要 4 字节浮点变量地址的转换函数。然后你的代码调用 Undefined Behaviour .

输出将是:

test@Linux:~/Test Folder$ ./test
10
bits: 01000001001000000000000000000000
sinal: +
expoente: 3
mantissa: 1.25000000

关于在 C 中将 float 转换为 IEEE 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36128024/

相关文章:

c - 调试 C 中的函数

c - 在c中初始化数组,格式为 `int a[3]={0,};`

c++ - 结构的区别?

c++ - 二进制比较

c++ - C++ 中的舍入和往返数字

c++ - 当一个相对较大的浮点值与两个相对较小的浮点值相乘时,消除误差的最佳算术顺序是什么

c - 在 C 语言中,%s 无法与我的返回值正常工作

c - C中的按位逻辑

python - 递归只打印一个列表

c++ - 将 float 转换为 bigint(也称为获取二进制指数和尾数的可移植方式)