0

In- Java , C# , Javascript :

AFAIU - the >> is a shift right operand which can deal also with signed numbers :

There is no problem with :

12>>2 --> 3

And also for signed number :

-12>>2 --> -3

But when the decimal result is not an integer , the result are differnt:

10>>2 --> 2

Whereas -10>>2 --> -3

I'm fully aware why it is happening (via Two's complement ) , but :

Question :

Does it mean that when I use the fastest division ever >> - I must check that :

10%4 is not zero ?

Am I missing something here ?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

1

You can use methods like Integer.numberOfTrailingZeros() and Long.numberOfTrailingZeros() to tell if shifting will be accurate or truncated.

You can also use bitwise AND to test the last bits, for example testing the last 4 bits:

int i = 543;
if ((i & 0x0f) == i )
    System.out.println("Last 4 bits are zeros!");

Although note that it's not worth using bit shift for "fast" division. You're not going to outsmart the compiler because most of today's compilers are intelligent enough to optimize these cases.

More on this: Is multiplication and division using shift operators in C actually faster?

Edit:

The answer to your question is that bit shifting is not defined as "the fastest division ever", it is defined as what its name says: bit shifting, which in case of negative numbers gives (or might give) different result.

You're not missing anything. If your input can be negative, your 2 options are:

  1. Either check the value and if it might give different result, corrigate it or use division. A simple check might be to test if it's negative, or test the last bits (described above).
  2. Completely avoid using bit shift for division purposes.
Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • Your answer talks about checking last bits . My question is not about checking but the issue that the division result is different via negative values – Royi Namir Jul 18 '14 at 08:17