0

I read that in java, negative integers are obtained by taking 2's complement of a positive integer. In short, it also means that the higher order bit is being set to 1 in order to convert a positive integer to negative integer. Out of curiosity I tried figuring out exactly which bit in an integer acts as the higher order bit in java. Now, the limit of integers in java is -(2^32) to ((2^32) - 1). So I decided if I keep on checking each of the 32 bit positions, I will come to know which one is the higher order bit.
Following is the code I used.

public class Main { public static void main(String[] args) { int x = 5; for(int i = 0; i<32; i++) { if((x|(1<<i)) == -5) { System.out.println(i + "th bit is the higher order bit"); } } } } 

But none of the bits came out to be the higher order bit. Which bit is it?

7
  • 4
    If you think that the binary representations of 5 and -5 differ only by the sign bit, you are mistaken. Commented Dec 8, 2020 at 8:34
  • Two's Complement is more than just signed magnitude. Commented Dec 8, 2020 at 8:36
  • The highest order bit of an int is the 31st bit, which is ordinarily left-most when printing. Commented Dec 8, 2020 at 8:45
  • 1
    Closed as a dupe because the question seems to be predicated on a misunderstanding of two's complement. Commented Dec 8, 2020 at 8:50
  • 1
    @Bathsheba I don't see why you reserve such contempt for Java; why aren't all language questions answered by their respective specifications? The problem isn't the spec, it's the squishy pulp trying to interpret it. Commented Dec 8, 2020 at 9:02

1 Answer 1

6

If you'll print the binary representation of 5and -5:

System.out.println (Integer.toBinaryString (5)); System.out.println (Integer.toBinaryString (-5)); 

You'll get:

101 11111111111111111111111111111011 

or, if we add the leading 0s:

00000000000000000000000000000101 11111111111111111111111111111011 

As you can see, the 2 representations differ in more than just the sign bit (which is the left most bit). Therefore your code is incorrect.

Setting the sign bit of the binary representation of 5:

System.out.println (5|(1<<31)); 

doesn't result in -5, it results in:

-2147483643 
Sign up to request clarification or add additional context in comments.

3 Comments

Looks like the odds are improving in my favour?
@Lino Indeed it isn't. But take a look at Eran's profile and to all the erudite answers of his that have been for questions that have been closed as duplicates of others. The Java tag is the one I used to follow that suffers from this misunderstanding of "duplicate" the most - by a country mile. It's that which I allude to.
@Bathsheba You just taught me a new word - erudite. Thanks for that :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.