This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hi all, My question is: 1)How does >> work?I tried to do -15>>1 by writing down -15 in bit pattern(11111111 11111111 11111111 11110001) and shifting it right 1 time.I get 11111111 11111111 11111111 11111000.How do I interpret this pattern? 2)Is there any easy way to do this rather than writing the whole bit pattern?The book that I am reading doesn't say much about this operator. Thank you Kant
Your answer for (1) is right so far - both (1) and (2) seem to come down to the same thing - how to interpret a negative number. First off - note that all the left hand bits are ones. As long as you know this in your head, you don't really need to write them all out. In this case, I'd just write maybe one byte's worth: -15 -> 11110001, right shift produces 11111000. To convert from negative binary to positive decimal:
Reverse the bits: 11111000 -> 00000111. You can now drop all the leading zeros too - we have 111.
Convert to decimal: 111 = 4 + 2 + 1 = 7.
Add 1: 8
Put a - sign in front: -8
And that's the answer: -8. Alternate methods for shift operations: Each time you shift left one bit, you multiply the value by two, e.g. 6 << 20 = 6 * 2^20 = 6291456. Unless you shift so far that bits fall off the left edge, 6 << 31 = 0 because all the bits have gone off the edge. Each time you shift right one bit, you effectively divide the number by two. The catch is, if the number is odd you have to round down, because you're losing a bit off the right edge. E.g. -15 >> 1 = -7.5 rounded down, which is -8. ("Down" for negative numbers means "towards a bigger negative value"). I suggest you practice with other values until you see that these methods are equivalent, and then use whichever you're more comfortable with.