我將在 Java 11 中實作一個類,以將部分十六進制字串轉換"8edb12aae312456e"為整數值。例如將位 18 到 23 轉換為整數值。我其實想要一個方法int hexStringToInt(String hexString, int fromBit, int toBit),所以我們在這個方法中應該有以下步驟:
將十六進制字串轉換為二進制陣列:
"8edb12aae312456e" -> 1000111011011011000100101010101011100011000100100100010101101110分離索引 18 到 23:
001001將其轉換為整數值,
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());
}
但我無法理解此輸出的含義以及如何將我的二進制陣列的一部分轉換為整數值。
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}
要點:
- 我不堅持使用Bitset。
- 正如您在我的示例中看到的,
"8edb12 ..."索引 8 和 9 不為零!
uj5u.com熱心網友回復:
這是一個單線,但一個巨大的:
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
}
您將索參考作基于一的約定是對 java 約定的厭惡。考慮使它們從零開始,這會稍微減少代碼,但主要是該方法的用戶會更熟悉。
PS在你提交這個作為家庭作業/能力測驗之前,確保你理解它,以防你被問到它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/426708.html
上一篇:為什么SpringBoot控制器在使用異步時不給出json回應?
下一篇:何時避免字串實習
