0

I'm writing a left shift algorithm in Java and have been doing some left shift calculations by hand. All of these numbers are typed as byte, btw.

Let's say I'm working with 8-bit integers from -128 to 127.

Then from my calculations:

(-113 << 4) == (-65 << 4) == -16

because

-113 == 1 0 0 0 1 1 1 1 
-113 << 4 == 1 1 1 1 0 0 0 0 == -16

but so does

-65 == 1 0 1 1 1 1 1 1
-65 << 4  == 1 1 1 1 0 0 0 0 == -16

So left shifting -113 by 4 and left shifting -65 by 4 result in the same value? Shouldn't all left shift operations produce unique values? Or do I have this right?

EDIT:

I'm working in Java and all of my numbers are bytes and the JVM is throwing an "error: loss of precision error" and this is what is also precipitating my question. Thanks!

Dimpermanence
  • 47
  • 1
  • 9

1 Answers1

1

This and many more shifting-related questions have been discussed in-depth in an SO question here. It also explains why your bits are counted differently when using signed expressions.

Concerning your question:

The same value from different source values issue you encountered comes from the fact that you're throwing information away by left-shifting bits out of the word. One of the formerly number-related information carrying bits has in both cases become the sign bit.

If you would have shifted -16 by only three bits, you would have even ended up with a positive number:

0 1 1 1 1 0 0 0 = 120

And, if you shifted out all of the bits (<< 8), you will also end up at the same value:

0 0 0 0 0 0 0 0 = 0

So you can indeed come up with the same number by shifting the bits of different values.

I hope that answers your question.

Community
  • 1
  • 1
  • Thanks, Jan. Makes sense! – Dimpermanence Jan 31 '16 at 07:11
  • Glad that helped. If you want the behavior you described (i.e., not lose information and always get a different number), you might want to look at **rotation** instead of shifting. –  Jan 31 '16 at 07:57