Bits means 1 or 0. These 1 or 0 usually use in base 2 counting numbers or binary numbers. Like for example a value of 15 in binary 1111. These operators were used to manipulate 1's and 0's.
Here are some those operators
1. Complement bitwise operator ( ~ )
- it inverts 0 to 1 or vice versa2. Bitwise AND ( & )
- it functions like Conditional AND but in bits or 1 and 0. So, if all values are 1 then, it returns a 1.3. Bitwise OR ( | )
- if any of the values is 1, it returns 1.4. Bitwise XOR ( ^ )
- as long as the bits are different, it returns a 1.
- A B RESULT
0 0 0
0 1 1
1 0 1
1 1 0================================
int x = 0b1101
int y = 0b1011
int z = x ^ z
System.out.println(z)=================================
Result:
6The results is 6 because this is a decimal but if converted to binary, the result is 0b0110.
How do we count or convert?
8 4 2 1
0 1 1 0The number on top is the equivalent in decimal. You only take the 1's and convert. So, 4 + 2 = 6.
Though, this doesn't end in 8 only, there are more if there are still 1 and 0 in front.
128 64 32 4 1
1 0 1 1 0 1 0 1 = 229Bitshift operators
1. Signed left shift operator ( << )
- it shifts the bit to the left.
2. Signed right shift operator ( >> )
- it shifts the bit to the right.
3. Unsigned right shift ( >>> )
- same with the signed right shift but the left most is converted to zero.
- like for example a decimal 4,
0b0100
In reality, what we presented is just a byte meaning 8 bits but the storage is in Gigabytes. Meaning it 1e9 bytes. So there will be lots of zeros in front...0b0000_0000_0000_0000_0000_0000...
0100- it will fill the leftmost with zeros as it shifts to the right.
- the result is different when you used a negative value for unsigned right shift. In inverts everything before it fills the left most with zero at it shifts to the right.================================
int x = 0b0100;
int z = x >> 1;
System.out.println(z);=================================
Result:
2The result is 2 we shifted the 1 to the left by 1. So, it becomes 0b0010.
================================
int x = 4;
int y = -4;
int za = x >>> 1;
int zb = y >>> 1;
System.out.println(za);
System.out.println(zb);================================
Result:
2
2147483646See the result for a 4 and -4 both shifted to the right by 1 using unsigned right shift operator.
YOU ARE READING
Java Programming
De Todohttps://docs.oracle.com/javase/tutorial/ This is the link where I learned my java lessons online. I choose java as first programming language. I am a career shifter. I just want to start something new. I choose to write it here in Wattpad so that I...