I'm looking for an in-depth explanation on how each of these bitwise functions work. I think I understand the underlying concepts of each, but I want to be sure. I'm looking for a piece by piece break down of each function.
Function 1
int logicalShift(int x, int n) {
x >>= n;
return x & ~(~(~0 << n) << (32 + ~n + 1));
Function 2
{ | int bang(int x) { |
int neg = ~x + 1; | |
return ((~(x | neg)) >> 31) & 0x1; | |
} | |
Function 3
int bitCount(int x) { | |
int mask1 = 0x55 + (0x55 << 8); | |
int mask2 = 0x33 + (0x33 << 8); | |
int mask3 = 0x0f + (0x0f << 8); | |
int mask4 = 0xff + (0xff << 16); | |
int mask5 = 0xff + (0xff << 8); | |
mask1 += mask1 << 16; | |
mask2 += mask2 << 16; | |
mask3 += mask3 << 16; | |
x = (x & mask1) + ((x >> 1) & mask1); | |
x = (x & mask2) + ((x >> 2) & mask2); | |
x = (x & mask3) + ((x >> 4) & mask3); | |
x = (x & mask4) + ((x >> 8) & mask4); | |
x = (x & mask5) + ((x >> 16) & mask5); | |
return x; |
Function 1:
In this function logical shift in which we shift var x to the right
by n moves. We can look at the limit that n is greater equal to 1
and lesser equal to 31.
Function 2:
In the bang function the bit which is on front ((~x) | x) is
always 1 for every number but not for 0
For 0 for the sign bit it doesn't matter it is positive or negative
but for others numbers it matter.
Function 3:
The purpose of this function is to return count of number of 1's
in word
We are using 5 integer type mask variables in which we are adding
memory location and shifting the address 8 bits to the left after
shifting all 5.
Now we are shifting 16bits to the left in mask1 mask2 mask3 by
adding their individual previous mask value.
Now we are finding value of x and shifting result to the right as
the binary power of 2
IF YOU HAVE ANY QUERY PLEASE COMMENT DOWN BELOW
PLEASE GIVE A THUMBS UP
Get Answers For Free
Most questions answered within 1 hours.