Skip to content

Instantly share code, notes, and snippets.

@joastbg
Created April 12, 2016 10:12
Show Gist options
  • Select an option

  • Save joastbg/3ba08d4af76915b8b0b76f8d64e51116 to your computer and use it in GitHub Desktop.

Select an option

Save joastbg/3ba08d4af76915b8b0b76f8d64e51116 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <cstring>
#include <bitset>
#include <cmath>
// Convert the 32-bit binary encoding into hexadecimal
int binary_to_hex(std::string &binary)
{
std::bitset<32> set(binary);
int hex = set.to_ulong();
return hex;
}
void parse_ieee754(std::string &binary) {
std::string sign = binary.substr(0,1);
std::string exp = binary.substr(1,8);
std::string frac = binary.substr(9,32);
std::cout << binary << " " << binary.length() << std::endl;
std::cout << sign << " " << sign.length() << std::endl;
std::cout << exp << " " << exp.length() << std::endl;
std::cout << frac << " " << frac.length() << std::endl;
}
// Convert the 32-bit binary into the decimal
float binary_to_f32(std::string &binary)
{
int hexNr = binary_to_hex(binary);
bool negative = !!(hexNr & 0x80000000);
int exponent = (hexNr & 0x7f800000) >> 23;
int sign = negative ? -1 : 1;
std::cout << "exp: " << exponent << ", sign: " << sign << std::endl;
// Subtract 127 from the exponent
exponent -= 127;
// Convert the mantissa into decimal using the
// last 23 bits
int power = -1;
float total = 0.0;
for ( int i = 0; i < 23; i++ )
{
int c = binary[ i + 9 ] - '0';
total += (float)c * (float)pow(2.0, power);
power--;
}
total += 1.0;
float value = sign * (float)pow(2.0, exponent) * total;
return value;
}
int main() {
std::string binary = "00111110001000000000000000000000";
std::cout << binary << std::endl;
parse_ieee754(binary);
std::cout << binary_to_hex(binary) << std::endl;
std::cout << binary_to_f32(binary) << std::endl;
unsigned long ul = 0x3E200000;
float f;
char *pul = (char *)&ul; // ok, char* can alias any type
char *pf = (char *)&f; // ok, char* can alias any type
memcpy(pf, pul, sizeof(float));
std::cout << f << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment