armorlord
armorlord

Reputation: 87

Converting a string holding binary to float

I have a string holding a value in binary that I want to convert to float. I can't find a way to do this.

for example, I have a

string temp =  "00000000000000000000000101111100";

to represent 0.25 in binary.

Using stof on temp with string::size_type yields 1.0111110e+008 stored in the float variable (according to visual studio) and printing the value results in junk - 101111104.

My question: is there a way to convert the binary string to a float directly or would I need to calculate the float and then store it?

Upvotes: 2

Views: 2181

Answers (2)

SwiftMango
SwiftMango

Reputation: 15294

Not sure why you would convert to float, but you can convert to unsigned long using std::bitset

#include <bitset>

//...

std::string temp =  "00000000000000000000000101111100";
std::bitset<33> n (temp);
unsigned long result = n.to_ulong();

REF

Of course you can cast unsigned long to float if you want.

Upvotes: 0

Axalo
Axalo

Reputation: 2953

This would be one way

std::string temp = "00000000000000000000000101111100";
assert(temp.length() == 32);
int n = 0;
for(int i = 0; i < temp.length(); ++i)
{
    n |= (temp[i] - 48) << i;
}
float f = *(float *)&n;

Upvotes: 4

Related Questions