# Using Java what is the best approach for doing hexadecimal to bit conversion?

Hello,

I have a hexadecimal String that I'm converting to its bit representation.  The Most significant byte iss Byte 0 and the most significant bit is bit 7.  So bits 1-4 which is the lower nibble.  For example, if I have a hex String of "01" and I want to get the decimal value of bits 1-4 of byte 1, I would use the below:
String tmp = "0145";
Integer value = Integer.parseInt(tmp.substring(1, 2), 16);

My question would be is there a built in Java function or best practice to then get the value (0 or 1) of bit 4 of the value variable above?  I have various bits I need to inspect to see if the values are 0 or 1.
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
not for Integer
What you could use is the BitSet class, or convert the value to a binary string and use charAt() method

0
Commented:
If you want to see of a bit is set or not set then convert the string to an int and use bit shift and mask. For example,

String hex = "0145";
int num = Integer.parseInt(hex, 16);
if( (num & (1 << bit)) != 0) {
// bit is set
else
// bit is not set

If you just want to convert the string to binary, change it to an int using Integer.parseInt then change it to a String using Integer.toBinaryString. The only trick for this is if you want to keep leading zeros. Full solution would be:

public static String hexToBinary(String hex) {
int i = Integer.parseInt(hex, 16);
String zeros = "00000000000000000000000000000000";
StringBuffer binary = new StringBuffer(Integer.toBinaryString(i));
String s = binary.insert(0, zeros, 0, numZeros).toString();
return s;
}

And if you had a different endianness:

public static String hexToBinaryReverse(String hex) {
int i = Integer.parseInt(hex, 16);
String zeros = "00000000000000000000000000000000";
StringBuffer binary = new StringBuffer(Integer.toBinaryString(i));
String s = binary.insert(0, zeros, 0, numZeros).reverse().toString();
return s;
}
0

Experts Exchange Solution brought to you by