user14387877
user14387877

Reputation:

Negative decimal to fixed-point binary

IS -28.91 = 00100.0111 ??

28 -> 11100 then flip and add 1 -28 -> 00100

.91 -> 0111 with the accuracy of 4 decimals places

I have tried to check a lot of places to check my conversion if it is correct but I am failing at it. So I like to ask people here if I am correct.

Upvotes: 1

Views: 1345

Answers (1)

Peter Cordes
Peter Cordes

Reputation: 364160

For addition / subtraction and other operations to work normally (by using binary addition on the whole bit-pattern), the whole thing (integer and fractional parts combined) as an integer has to be x * 2^4.

i.e. the actual value represented by 0b00100.0111 is 0b001000111 / 16.

That means you have to do 2's complement negation (binary subtraction from 0, or use the invert and add 1 identity) for the whole and fractional bits together.

Also, your value for 28 has its MSB set, so it's already negative, i.e. you've overflowed 5-bit signed 2's complement. Presumably you actually have a wider integer part.

For 16-bit 12.4 fixed-point, 28.91:

  • 28.91 * 16 = 462.56, which rounds up to 463.
  • +463 = 0b0000000111001111
  • -463 = 0b1111111000110001

As 12.4 fixed-point, this 0b111111100011.0001 bit-pattern represents -463/16 = -28.9375, the nearest representable value to -28.91

Upvotes: 1

Related Questions