• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 296
  • Last Modified:

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.  
0
cgray1223
Asked:
cgray1223
1 Solution
 
objectsCommented:
not for Integer
What you could use is the BitSet class, or convert the value to a binary string and use charAt() method

0
 
dgraingerCommented:
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));
            int numZeros = Integer.numberOfLeadingZeros(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));
            int numZeros = Integer.numberOfLeadingZeros(i);
            String s = binary.insert(0, zeros, 0, numZeros).reverse().toString();
            return s;
      }
0

Featured Post

The 14th Annual Expert Award Winners

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

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