简体   繁体   中英

Bitwise operation 111&011=9, how?

The bitwise operation 111&011 is giving output as 9 in java. how? 111&011 should be 011, ie 3.

You're specifying the numbers as decimal and octal , not as binary as you assume.

           number  | decimal value | binary  
           --------- -----------------------
(decimal)  111     | 111           | 1101111 
(octal)    011     | 9             | 0001001     

so:

   1101111
&     1001
   -------
   0001001

and 1001 = 2^3 + 1 = 9

to check it out use Integer.toBinaryString

public static void main (String[] args) {
  System.out.println(
    Integer.toBinaryString(111));

  System.out.println(
    Integer.toBinaryString(011));

  System.out.println(111 & 011);
}

code on ideone

Complementing yaitloutou's answer : an integer literal can be represented in different bases in Java:

  • 0 , just the digit zero (base does not matter, but specified as decimal)
  • decimal : a non-zero decimal digit eventually followed by decimal digits, eg 20
  • hexadecimal : 0x followed by one or more hexadecimal digits, eg 0x14
  • octal : 0 followed by one or more octal digits, eg 024
  • binary : 0b followed by zeros and ones, eg 0b10100

The underscore _ can be used to separate digits, it will be ignored, eg 0b0001_0100

See the Java Language Specification 3.10.1 for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM