Mar 5

Converting hex to Binary in Java Too

Category: Java, Programming

So apparently the hex to binary in 4 languages portion of this web page is what gets the most google hits and who am I to argue? So without further ado, hex to binary in Java as well…

The Program

So to recap what I want to do, I want to take an ASCII hex string on STDIN and turn it into a binary representation of that hexadecimal string on stdout thusly:

cat 00 01 02 03 04 | ./myscript > binary_out


So In java this is somewhat more annoying than the scripting languages from the previous article.

package com.fourth mouse.htod;
class HexToBinary{
    private static String readAllStdIn() throws IOException{
        BufferedReader stdInReader
            = new BufferedReader(new InputStreamReader(;
                String input = "";
                String line;
                while( (line = stdInReader.readLine()) != null){
                        input = input + line;
        return input;
    private static char packHexByte(String s){
        char ret = (char)Character.digit(s.charAt(1), 16);
        ret = (char)(ret |
              (Character.digit(s.charAt(0), 16) << 4));
        return ret;
    public static void main(String []args) throws IOException{
        String input = readAllStdIn();
        input = input.replaceAll("\\s", "");
        for(int i=0; i < input.length()/2; i++){
            char c = packHexByte(input.substring(i*2, i*2+2));

There are a lot of considerations here. So I’ll break them out.

Java IO

There is a lot positive to be said about java IO. This is particularly the case when compared to C++ IO. That being said it does seem to have a bit of a schizophrenic personality. There are Input/Ouput streams, Reader/Writer objects, and now the java.nio channels business. If you want readLine first you have to figure out which of the things provides that most basic functionality (and of course does not) and then figure out how to take what you have and turn it into what you want.

Worse if you want to define a generic library it isn’t at all clear what type of stream/reader/writer/channel you should expect in your interface and why. Should it be buffered? etc, etc…

Regex Support Patched In

Java didn’t support regular expressions out of the box as part of the language so they were added in as a library afterwards. Since Java went out of its way to discourage things like operator overloading that make for the more interesting domain specific languages they were not integrated in a graceful way. As a result I have to use \\s to get \s. This is a minor nit, but since a lot of other languages built in regular expressions from the start it’s annoying.

No Unsigned Types

Java doesn’t have any unsigned types. When you are doing binary shift operations and so forth you need to be aware of this. The standard shift operators retain sign by extending the sign bit which isn’t what you want to happen when you are doing binary data. Java has some non-sign-preserving operators <<< and >>> that do not extend the sign bit. This can also be a problem when casting from a char to larger type which will also result in the sign bit being extended. In this case it isn’t actually a problem, but it’s worth noting.


This is a little unfair to compare with scripting languages, but the overhead in Java to do something like this is pretty high. You have to

  1. Declare a package
  2. Create a directory for the package
  3. Define a bunch of imports
  4. Define a class
  5. Explicitly declare exceptions

The Author

Michael Smit is a software engineer in Seattle, Washington who works for amazon

Comments are off for this post

Comments are closed.