This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori 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.

Jim, I've a very basic question, which I'm getting for confused for a while and am not able to find the solution anywhere. HOW TO CONVERT A NEGATIVE INTEGER TO BINARY??? Any easy way to that???

Your help will be very much appreciated. Prabhu.

Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671

posted

0

It's the reverse of the process I gave above. Negative decimal to binary (using -15 as example):

Drop the negative sign (-15 -> 15)

Subtract 1. (15-1 = 14)

Convert to binary (14 -> 1110)

Reverse all digits, being sure to include enough leading 1's for the number of bits in the datatype (using int, 1110 -> 11111111 11111111 11111111 11110001)