TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Home » Tip Bank » XML » XML with Java
Language: Java Language
Expertise: Beginner
Oct 15, 1999

WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

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

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) {

length+=begin;

for(int i=begin; i < length; ++i) {
System.out.print('0');
else
System.out.print('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

 Submit a Tip Browse "XML" Tips Browse All Tips
Comment and Contribute

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

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