Tuesday, 15 March 2011

bitwise operators - Use of | in java -


I came across a Java code in which the constant is defined in the following way

  Fixed last four FM = (four) (ConstantsSystem.DOUBLE_BYTE_SEP | 0xFE);   

In this code | What is the use of ?

| is a bitword or operator. It works as follows:

  0 | 0 == 0 0 | 1 == 1 1 | 0 == 1 1 | 1 == 1  

Internally, an integer is represented as a sequence of bits. So if you have, for example:

  int x = 1 | 2;  

This would be equivalent:

  int x = 0001 | 0010; Int x = 0011; Int x = 3;  

Note I am using only 4 bit for clarity, but in Java it is represented by a int 32 bits.

For example, if we believe that ConstantsSystem.DOUBLE_BYTE_SEP is 256:

  Fixed last four FM = (four) (ConstantsSystem.DOUBLE_BYTE_SEP | 0xFE); Fixed last four FM = (four) (256 | 254); Fixed last four FM = (four) (0000 0001 0000 0000 | 0000 0000 1111 1110); Fixed last four FM = (four) (0000 0001 1111 1110); Fixed last four FM = (four) (510); Fixed last four FM = 'วพ';  

Also keep in mind that the way I wrote a binary number is not how you represent binary in Java. For example:

  0000 0000 1111 1110 will be:  
  0b0000000011111110  

Documentation:


No comments:

Post a Comment