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
Oct 15, 1999

Binary Representation of a Char

Question:
How can I get the binary representation of a letter or number?

For example, the letter "A" is 100 0001, the letter "B" is 100 0010, etc...

Answer:
You can obtain the individual bits in an integer by anding it with a bitmask that contains a one bit in the position you are fetching and zero bits in all the other positions.

If the result of the and is zero, then that bit is not set, otherwise the bit is set. To print out all of the bits in a number, you can write a loop where you shift the bitmask and perform this test for each bit.

In the following code example I have written a generalized function that uses this principle to print out a range of bits in an integer.

public class PrintBits {

  // Doesn't do bounds checking
  public static void printBits(int number, int begin, int length) {
    int bitmask;

    bitmask = 0x80000000 >>> begin;
    length+=begin;

    for(int i=begin; i < length; ++i) {
      if((number & bitmask) == 0)
        System.out.print('0');
      else
        System.out.print('1');
      bitmask >>>= 1;
    }
    System.out.println();
  }


  public static void main(String[] args) {
    for(char ch='A'; ch <= 'Z'; ++ch)
      // Print the last 8 bits of the character.
      printBits(ch, 24, 8);
  }
}

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