Search code examples
cbinaryieee-754ieee

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. 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. 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:

bits: 01000001001000000000000000000000

sinal: +

expoente: 3

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

Solution

  • You can fix your weird code modifying first instructions of 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. Then your code invoke Undefined Behaviour.

    Output will be:

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