Monday 26 November 2012

Puzzle 5: What does it mean by Hex and Octal literals are negative if their high-order bit is set?

In the book, "Java Puzzle", Puzzle 5: The Joy of Hex, there is a bold line Hex and Octal literals are negative if their high-order bit is set to explain the number 0xcafebabe is equivalent to the decimal value -889275714.

So what does "high-order bit is set" mean?

"high-order bit" is the left most bit of a given type. For example, if type is integer, which has 32 bits, then the high-order bit is the 32nd bit counting from right to left.

The 32nd bit counting from right to left is 0 in the following case, so the number is a positive number

int max = Integer.valueOf("01111111111111111111111111111111", 2);
System.out.println(max);

The result is

2147483647

which happens to be the maximum integer number.

Now let's convert the Hex format number 0xcafebabe to binary format

String s = Integer.toBinaryString(0xcafebabe);

The result is

11001010111111101011101010111110

The high-order bit is 1, therefore, it is a negative number.

6 comments:

  1. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up..
    web designing training in chennai

    web designing training in omr

    digital marketing training in chennai

    digital marketing training in omr

    rpa training in chennai

    rpa training in omr

    tally training in chennai

    tally training in omr



    ReplyDelete