[英]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}
要點:
"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.