简体   繁体   English

在 C 中将浮点数转换为 IEEE 格式

[英]Converting float to IEEE format in C

I need to transform a float to IEEE (the float is given by a scanf, and it has to come from the scanf otherwise it will drop and error) and I don't seem to get it to work.我需要将浮点数转换为 IEEE(浮点数由 scanf 给出,它必须来自 scanf,否则它会丢失并出错),但我似乎无法让它工作。 I tried using argc and argv and it was correct but my submitting platform didn't accept it because I need to get the float by a scan.我尝试使用 argc 和 argv 并且它是正确的,但我的提交平台不接受它,因为我需要通过扫描获取浮点数。 The problem is since I'm trying to use the scan, it won't print the correct Bits.问题是因为我试图使用扫描,它不会打印正确的位。

The output for the number 10 should be:数字 10 的输出应为:

bits: 01000001001000000000000000000000位:01000001001000000000000000000000

sinal: +信号:+

expoente: 3被试:3

mantissa: 1.25000000尾数: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;
}

You can fix your weird code modifying first instructions of main:您可以修复修改 main 的第一条指令的奇怪代码:

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

In your code you are passing a global char variable to the conversion function that expects a 4 bytes float variable address.在您的代码中,您将一个全局char变量传递给需要4字节浮点变量地址的转换函数。 Then your code invoke Undefined Behaviour .然后您的代码调用Undefined Behavior

Output will be:输出将是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM