在C中将float转换为IEEE格式

时间:2016-03-21 10:05:59

标签: c binary ieee-754 ieee

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

数字10的输出应为:

位:01000001001000000000000000000000

sinal:+

expoente: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;
}

1 个答案:

答案 0 :(得分: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