-2

I have a bit problem. Given: some real number(for example -474.875) Task: extract BINARY value of mantissa For number -474.875 I need this value 1,11011010111 * 2^8 I have a programm:

const float d = -474.875f;
int exponent;
const float mantissa = frexp(d, &exponent);
double prev = mantissa * pow(2, exponent);

It calculates decimal mantissa (for my number it is -0.927490234) and exponent (9). I'm tried to convert this mantissa to binary... but failed... I got other value. To get original value: mantissa* 2^exponent. QUESTION: How I can get binary value of mantissa? May be it is possible to do it in more pretty way?

aleksher
  • 3
  • 4
  • 2
    You may want to look at the IEEE floating point format specification for your compiler. You can extract the mantissa, then convert to binary. – Thomas Matthews Sep 28 '18 at 18:22
  • @ThomasMatthews: Per the code in the question, they already have the significand (the preferred name for the fraction part of a floating-point object; a mantissa is the fractional part of a logarithm). They do not need to refer to the IEEE-754 format. – Eric Postpischil Sep 28 '18 at 18:47
  • Obviously you have to convert -0.927490234*2 – gammatester Sep 28 '18 at 19:25

2 Answers2

1

You may want to use an union with your float and an int. That way you'll will be able to do some binary operations, like extracting the mantissa.

These links may help you :

Floating Point to Binary Value(C++)

Binary representation with union

SkR
  • 82
  • 1
  • 11
1

After const float mantissa = frexp(d, &exponent);, the value in mantissa is a number. It is not a decimal numeral. You can convert it to binary with:

float s = fabs(mantissa)*2;
std::cout << "The significand is " << (int) s << ".";
s = s - (int) s;
while (0 != s)
{
    s *= 2;
    std::cout << (int) s;
    s = s - (int) s;
}
std::cout << ".\n";

For the sample value you show, this prints “The significand is 1.11011010111.”

The code simply multiplies the value by two to move the next bit “above” the decimal point. Then converting it to int produces that bit. Then the bit is removed and the process is repeated until all significant digits have been extracted.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312