devxlogo

Single bit assignment

Single bit assignment

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.");  }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist