Home > OS >  How I can convert a part of Hex String to Integer value in Java
How I can convert a part of Hex String to Integer value in Java

Time:02-19

I am going to implement a class in Java 11 to Convert a part of hex string like "8edb12aae312456e" to integer value. For example convert from bit 18 to 23 to integer value. I actually want a method int hexStringToInt(String hexString, int fromBit, int toBit), so we should have the following steps in this method:

  • Convert hex string to binary array: "8edb12aae312456e" -> 1000111011011011000100101010101011100011000100100100010101101110

  • Seperate index 18 to 23: 001001

  • Convert it to Integer value, 001001 -> 9

I try to use Bitset in following code:

public static BitSet hexStringToBitSet(String hexString) {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    for(int i = 0; i < hexString.length() - 1; i  = 2) {
        String data = hexString.substring(i, i   2);
        bout.write(Integer.parseInt(data, 16));
    }
    return BitSet.valueOf(bout.toByteArray());
}

But I could not understand the meaning of this output and how can I convert a part of my binary array to Integer value.

BitSet bitSet = hexStringToBitSet("8edb12aae312456e");
System.out.println(bitSet);
//{1, 2, 3, 7, 8, 9, 11, 12, 14, 15, 17, 20, 25, 27, 29, 31, 32, 33, 37, 38, 39, 41, 44, 48, 50, 54, 57, 58, 59, 61, 62}

Points:

  1. I do not insist on using Bitset.
  2. As you see in my example,"8edb12 ..." the index 8 and 9 are not zero!!

CodePudding user response:

It's a one-liner, but a whopper:

public static int hexStringToInt(String hexString, int fromBit, int toBit) {
    return Integer.parseInt( // parse binary string
       Arrays.stream(hexString.split("(?<=.)")) // split into individual chars 0-f
       .mapToInt(c -> Integer.parseInt(c, 16)   16) // parse hex char to int, adding a leading 1
       .mapToObj(Integer::toBinaryString) // int to 1's and 0's
       .map(b -> b.replaceFirst("1", "").split("(?<=.)")) split to binary digits
       .flatMap(Arrays::stream) // stream them all as one stream
       .skip(fromBit - 1) // skip the "from"
       .limit(toBit - fromBit   1) // stop after "to"
       .collect(joining()), 2); // join binary digits together, parse as base 2
}

Your convention of using your indexes as one-based is anathema to java convention. Consider making them zero-based, which would slightly reduce the code but mainly would be more familiar to users of the method.


P.S. Before you submit this as homework/aptitude test, make sure you understand it in case you are quizzed on it.

  • Related