Extract numbers from a 32-bit integer

I am trying to solve a puzzle in a programming test.

Disclaimer: This is a test for work, but I'm not looking for an answer. I'm just looking for an understanding of how to do this. The test requires that I come up with a set of solutions to solve problems within 2 weeks, and it does not indicate that I come to solutions in isolation.

So the problem is:

I have a 32-bit number with bits sorted like this:

siiiiiii iiiiiiii ifffffff ffffffff

Where:

  • s - sign bit (1 == negative)
  • i'm 16 whole bits
  • f - 15 bit fractions

The purpose is to write something that decodes a 32-bit integer to a floating point number. Given the following inputs, it should produce the following results:

input            output

0x00008000   1.0
0x80008000  -1.0
0x00010000   2.0
0x80014000  -2.5
0x000191eb  3.14
0x00327eb8    100.99

I have no problem getting a bit of a character or the integer part of a number. I get the sign bit as follows:

boolean signed = ((value & (1 << 31)) != 0);

:

int wholePart = ((value & 0x0FFFFFFF) >> 15);

int fractionPart = ((value & 0x0000FFFF >> 1));

, , 15 , . 3.14 3.4587 ..

- , , . , , .: -)

+3
5

. , . , , . , , ?

+4

...

int fractionPart = value & 0x00007FFF;  // i.e. no shifting needed...

, ,

boolean signed = ((value & (0x80000000) != 0);  // signed is true when negative

. , .. , ... ', ...

+2

, .

+1
int wholePart = ((value & 0x7FFFFFFF) >> 15);

int fractionPart = (value & 0x00007FFF);

, ...

0

31 1 = Neg 0 = Pos

BEFORE siiiiiii iiiiiiii ifffffff ffffffff
SHR 31 00000000 00000000 00000000 0000000s

1, Shift Right 16 Integer

BEFORE siiiiiii iiiiiiii ifffffff ffffffff
SHL 1  iiiiiiii iiiiiiii ffffffff fffffff0
SHR 16 00000000 00000000 iiiiiiii iiiiiiii

Shift Left 17, Shift Right 15 Faction

BEFORE siiiiiii iiiiiiii ifffffff ffffffff
SHL 17 ffffffff fffffff0 00000000 00000000
SHR 16 00000000 00000000 0fffffff ffffffff

0

Source: https://habr.com/ru/post/1722291/


All Articles