0

How can I take binary representation of float-pointing types? Or how can I take mantissa and exponent of float-pointing number?

Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120
AC130
  • 27
  • 4

6 Answers6

3

Look at frexp function to get significand and exponent: http://www.cplusplus.com/reference/cmath/frexp/

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
2

I don't know if this is the best way and probably depends on the compiler, but you can create a union of appropriately sized unsigned integer and the floating-point type. Assign the float, and read the int.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
2

you can use unions

union converter
{
  float number;
  struct
  {
    unsigned int mantisa  : 23;
    unsigned int exponent : 8;
    unsigned int sign     : 1;
  } binary;
};

With this structure you can extract mantisa, exponent and sign data easily:

union converter convert;

convert.number = 24.6;
int mantisa = convert.binary.mantisa;
int exponent = convert.binary.exponent;
int sign = convert.binary.sign;
eferion
  • 872
  • 9
  • 14
1
#include<iostream>
using namespace std;

int main(){
    float test{ 9.9f };
    unsigned char *print{ (unsigned char *)&test };
    unsigned int mask{ 1 };
    for (int i = sizeof(float) - 1; i >= 0; --i){
        unsigned int temp{ print[i] };
        for (int i = 7; i >= 0; --i)
            cout << ((temp & (mask << i)) >> i);
    }
cout << endl;
return 0;
}

for double type just substitudes those two floats in code.

please note that this code only work for little-endian machine and the output i got is 01000001000111100110011001100110

RogerTR
  • 49
  • 2
1

Little-Endian:

void func(float f)
{
    char  arr[sizeof(f)];
    char* ptr = (char*)&f;
    for (int i=0; i<sizeof(f); i++)
        arr[i] = ptr[i];
    // Now use 'arr' as you will...
}

Big-Endian:

void func(float f)
{
    char  arr[sizeof(f)];
    char* ptr = (char*)&f;
    for (int i=0; i<sizeof(f); i++)
        arr[i] = ptr[sizeof(f)-1-i];
    // Now use 'arr' as you will...
}
barak manos
  • 29,648
  • 10
  • 62
  • 114
0

If you want to obtain the binary representation of a floating point type then using a union and std::bitset seems the quickest way to go.

In C we know type punning though a union is ok(see my footnote here) but in C++ it is a not clear so it would be better to go with a compiler that explicitly supports it such as gcc which documents this support in C++.

A quick implementation would be as follows (see it live):

#include <bitset>
#include <iostream>

union floatToInt
{
   float f ;
   unsigned int u ;
} ;

int main()
{
    floatToInt u1 ;

    u1.f = 3.4f ;

    std::bitset<32> bs1( u1.u ) ;

    std::cout << bs1 << std::endl ;
}

with the following result:

01000000010110011001100110011010

which if we plug this into IEEE 754 Converter, gives us back 3.4.

Community
  • 1
  • 1
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740