Converting a Hex String to N-bit Binary String

Recently I have wanted to keep track of unique IDs of the Android devices using one of my applications. These are found under Settings.Secure.ANDROID_ID and are 64bit numbers given as Hex Strings, but I needed the actual binary number, with leading zeros included. I did a lot of research but couldn’t find a complete elegant solution, so here is what I came up with:

	private static String hexStringToNBitBinary(String hexString, int N){
		long decimalResult = 0;
		int length = hexString.length(); //store the length in memory, for devices without a JIT
		int i;
		
		for (i = 0; i < length; i++){
			//equivalent to multiplying the result by 16 and adding the value of the new digit, but uses bit operations for performance
			decimalResult = (decimalResult << 4 ) | Character.digit(hexString.charAt(i), 16);
		}
		String binary = Long.toBinaryString(decimalResult); //gives us a binary string, but is missing leading zeros
		length = binary.length();
		if (length == N){
			return binary;
		}  else if (length < N){
			int difference = N-length;
			char[] buffer = new char[N]; //allocate a new char buffer of the desired length 
			for (i = 0; i < difference; i ++){
				buffer[i] = '0'; //fill in the needed number of leading zeros
			}
			binary.getChars(0, length, buffer, difference); //copies the original binary string into the buffer after leading zeros
			return new String(buffer);
		} else{
			throw new IllegalArgumentException("Hex String is not a N bit number!");
		}
	}

I believe that this is has better performance than using String concatenations or StringBuilder appends, since we allocate just the number of memory we know we need immediately. Let me know if there is a more efficient way.

Advertisements
This entry was posted in Programming and tagged , , , . Bookmark the permalink.

One Response to Converting a Hex String to N-bit Binary String

  1. juned says:

    Thanks this is a real conversion of Hex to Binary

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s