繁体   English   中英

如何将部分十六进制字符串转换为 Java 中的 Integer 值

[英]How I can convert a part of Hex String to Integer value in Java

我将在 Java 11 中实现一个 class 以将部分十六进制字符串(如"8edb12aae312456e"转换为 integer 值。 例如,从位 18 到 23 转换为 integer 值。 我实际上想要一个方法int hexStringToInt(String hexString, int fromBit, int toBit) ,所以我们应该在这个方法中有以下步骤:

  • 将十六进制字符串转换为二进制数组: "8edb12aae312456e" -> 1000111011011011000100101010101011100011000100100100010101101110

  • 单独索引 18 到 23: 001001

  • 将其转换为 Integer 值, 001001 -> 9

我尝试在以下代码中使用Bitset

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());
}

但是我无法理解这个 output 的含义,也无法理解如何将二进制数组的一部分转换为 Integer 值。

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}

要点:

  1. 我不坚持使用Bitset
  2. 正如您在我的示例中所见, "8edb12..."索引 8 和 9 不为零!

这是一个单行,但是一个弥天大谎:

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
}

您将索引用作基于 one 的约定是对 java 约定的诅咒。 考虑使它们从零开始,这会稍微减少代码,但主要是该方法的用户会更熟悉。


PS 在您将此作为家庭作业/能力测试提交之前,请确保您理解它以防您被测验。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM