Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

Tip of the Day
Language: Java Language
Expertise: Beginner
Oct 15, 1999



Application Security Testing: An Integral Part of DevOps

Binary Representation of a Char

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...

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;

    for(int i=begin; i < length; ++i) {
      if((number & bitmask) == 0)
      bitmask >>>= 1;

  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.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date