The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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.

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

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.

1 Solution

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 = "0000000000000000000000000

StringBuffer binary = new StringBuffer(Integer.toBin

int numZeros = Integer.numberOfLeadingZer

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 = "0000000000000000000000000

StringBuffer binary = new StringBuffer(Integer.toBin

int numZeros = Integer.numberOfLeadingZer

String s = binary.insert(0, zeros, 0, numZeros).reverse().toStri

return s;

}

Tackle projects and never again get stuck behind a technical roadblock.

Join Now
What you could use is the BitSet class, or convert the value to a binary string and use charAt() method