I love to see people writing Bit Twiddling code but I just can't understand it at all. Gone through Hacker's Delight and http://graphics.stanford.edu/~seander/bithacks.html, but I failed to understand anything.
For example:
How come 1 | 2
returns 3
or how come a ^=b; b ^= a; a ^=b;
swap the values etc...
One method:
private T[] ensureCapacity(int minCapacity) {
if (tmp.length < minCapacity) {
// Compute smallest power of 2 > minCapacity
newSize |= newSize >> 1;
int newSize = minCapacity;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
newSize++;
if (newSize < 0) // Not bloody likely!
newSize = minCapacity;
else
newSize = Math.min(newSize, a.length >>> 1);
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
T[] newArray = (T[]) new Object[newSize];
tmp = newArray;
}
return tmp;
}
What the below likes are doing:
int newSize = minCapacity;
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
newSize++;
or
newSize = Math.min(newSize, a.length >>> 1);
Better to use >>
or >>>
operator I mean after Joshua Bloch fixed the broken binary search I understand that it's safe to use >>>
instead >>
. Please help and if there is a tutorial then the above mentioned source I will appreciate that very much.
What is the easiest way to calculate the output of bits for example 1 | 2 = 3
?
I mean I don't know how the bit form looks except I use a calculator or something.. Is there any easiest way to calculate these things without any help but in mind?