Only if that integer is padded with leading 0's. Remember, an
int is a signed integer, so you're dealing with signed arithmetic. Be careful of leading 1's.
In an 8 bit signed integer:
00010001 = 17
11110001 = -15
The leading bit in a signed integer is the signed bit where a 1 represents a negative integer and a 0 represents a positive one, so you must somehow be getting a 1 in the signed bit position. To calculate the decimal value of a
negative binary number, you first have to take the 1's complement then add 1 to it:
So in the above 8 bit example:
11110001 = - (00001110 + 00000001) = - (00001111) = -15
The << and >> bit shift operators move bits to the left and right a specific number of positions. I *think* it'll also roll over, meaning if you shift left or right past the last bit position, it'll bring the bit around on the other end. A >>> discards anything shifted beyond the right most bit position and 0 fills from the left. The equation looks to be trying to strip off the unwanted leading bits then shifting down and zero padding, but I think it's off slightly.
Ex: INT_SIZE is 8.
Passing in a 17 (00010001) and requesting bit 5 (17, 5, 5) would result in:
nShift = 8-1-5 = 2;
((00010001 << 2)) >>> (2 + 5)) = ((01000100) >>> (7)) = 0!
So, it looks like the formula is slightly off. Here's a suggested tweak:
Code: Select all
int nShift = INT_SIZE - nEndBit;
((nNum << nShift) >>> (nShift + nStartBit - 1));
Ex: INT_SIZE is 8.
Passing in a 17 (00010001) and requesting bits 1-5 (17, 1, 5) would result in:
nShift = 8-5 = 3;
((00010001 << 3) >>> (3 + 1 - 1)) = ((10001000) >>> (3)) = 17
That look ok? What number are you passing into this function? There's always the possibility that the >>> operator is broken and isn't 0 padding or something.