Reputation: 44
I came across a java code in which the constant has been defined in the following way
static final char FM = (char) (ConstantsSystem.DOUBLE_BYTE_SEP | 0xFE);
what is the use of |
in this code?
Upvotes: 1
Views: 98
Reputation: 9049
The |
is the bitwise 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 to:
int x = 0001 | 0010;
int x = 0011;
int x = 3;
Note I am using only 4 bits for clarity, but an int
in Java is represented by 32 bits.
Specifically addressing your code, if we assume, for example, that the value of ConstantsSystem.DOUBLE_BYTE_SEP
is 256:
static final char FM = (char) (ConstantsSystem.DOUBLE_BYTE_SEP | 0xFE);
static final char FM = (char) (256 | 254);
static final char FM = (char) (0000 0001 0000 0000 | 0000 0000 1111 1110);
static final char FM = (char) (0000 0001 1111 1110);
static final char FM = (char) (510);
static final char FM = 'Ǿ';
Also note that the way I wrote the binary numbers is not how you represent binaries in Java. For example:
0000 0000 1111 1110
would be really:
0b0000000011111110
Documentation: Bitwise and Bit Shift Operators
Upvotes: 8