Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Feb 26, 1998

Single bit assignment

Question:
Is there an easy way to assign each bit in a byte, and how do I access those bits individually?

Answer:
Usually, if you come from a C programming background, you will already have 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 has four bitwise operators (which the answer submission program won't let me include for some reason).

bitwise complement
bitwise OR
bitwise AND
bitwise XOR

You can use these operators to set, unset, and otherwise change the values of individual bits. To set a bit you will generally use the OR operator and to fetch a bit you will use the AND operator, both in conjunction with a bit mask defining the bit to be affected. As a 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.");
  }

}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date