Monday, March 21, 2005

Binary Numbers

Introduction

The following methods can be used to convert binary numbers in Java:

  • public static String toBinaryString(int i)
  • public static String toBinaryString(long i)
  • public static int parseInt(String s, int radix) throws NumberFormatException
  • public static long parseLong(String s, int radix) throws NumberFormatException

Program

package bloggingjava;

class Main {
    public static void main(String[] args) {
        System.out.println(Integer.toBinaryString(42));
        System.out.println(Integer.parseInt("10101010", 2));
    }
}

Output

[user]$ javac Binary.java
[user]$ java Binary
101010
170

Discussion

According to The Hitchhiker's Guide to the Galaxy, the Ultimate Answer to Life, the Universe, and Everything is 42. "As any digital hardware engineer, or software engineer, can tell you, the number '42' in base ten is equal to '101010' in base two. This alternating pattern of ones and zeros illustrates DEEP Thought's indecision about the Ultimate Question." (http://www.digitalthoughtsw.com/DTS/42/). However, the smallest number of bits a computer can work with is 8 bits, called a byte. 42 in binary is not 101010, but 00101010. The answer, then, should be 10101010 which is 170, not 42. So, the theory about Deep Thought being indecisive about the answer to the Ultimate Question seems to be wrong.

Resources

2 comments:

Fist said...

There are only 10 types of people in this world. Those who understand binary, and those who don't.

Anonymous said...

That's only 2 types. To get 10 types, you need those who understand binary, those who don't, and the smartarses who prefer trinary.