Reputation: 27
How can I take binary representation of float-pointing types? Or how can I take mantissa and exponent of float-pointing number?
Upvotes: 0
Views: 310
Reputation: 158469
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
.
Upvotes: 0
Reputation: 30136
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...
}
Upvotes: 1
Reputation: 902
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;
Upvotes: 2
Reputation: 49
#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
Upvotes: 1
Reputation: 20993
Look at frexp
function to get significand and exponent: http://www.cplusplus.com/reference/cmath/frexp/
Upvotes: 3
Reputation: 21773
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.
Upvotes: 2