Question:
Is there an easy way to assign each bit in a byte, and how do Iaccess those bits individually?
Answer:
Usually, if you come from a C programming background, you will alreadyhave some experience twiddling bits. But if Java is your first language,or you’re coming from a language that does not allow bit-manipulation,then this process may be unfamiliar to you. Just like C, Java hasfour bitwise operators (which the answer submission program won’t let me includefor some reason).
- bitwise complement
- bitwise OR
- bitwise AND
- bitwise XOR
You can use these operators to set, unset, and otherwise change thevalues of individual bits. To set a bit you will generally use theOR operator and to fetch a bit you will use the AND operator, bothin conjunction with a bit mask defining the bit to be affected. Asa simple example, let’s fetch the lowest order bit of a byte, set it,and test it again:
public final class Bits { public static final void main(String[] args) { byte b; int lowOrderMask = 0x0001; b = 0; if((b AND lowOrderMask) != 0) System.out.println("Low order bit is set."); else System.out.println("Low order bit is not set."); b OR= lowOrderMask; if((b AND lowOrderMask) != 0) System.out.println("Low order bit is set."); else System.out.println("Low order bit is not set."); }}