r/javaTIL • • Jun 20 '15

TIL the inverse of left shift

inb4 "the opposite is right shift"

given:
x = 1 << y;

expect:
y == 31 - Integer.numberOfLeadingZeros(x);

In C this is usually the clz function.

6 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/Simaldeff Oct 17 '15

Ok my bad, should have read more carefully. Unless you keep a variable that tells you if the bit you lost is a 1 or a 0. This is the problem when you lose information ... you lose it.

1

u/karlthepagan Oct 17 '15

A good use case for this function is to calculate a magnitude or mask.