gpt4 book ai didi

java - 如何确定十六进制字符串中是否设置了某个位?

转载 作者:行者123 更新时间:2023-12-02 12:14:05 24 4
gpt4 key购买 nike

我有一个十六进制格式的字符串,例如:

AAE04471

在我看来,在二进制 View 中该字符串必须如下所示:

10101010 11100000 01000100 01110001

我试图确定 32 位是否设置如下:

 String s = "AAE04471";
byte[] bytes = DatatypeConverter.parseHexBinary(s);
System.out.println("Length bytes[] = " + bytes.length);
BitSet bitset = BitSet.valueOf(bytes);
System.out.println("Length of bitset = " + bitset.length());
System.out.println("Look of bitset = " + bitset.toString());
System.out.println("32 bit is " + bitset.get(31));

我得到“错误”结果:

Length bytes[] = 4
Length of bitset = 31
Look of bitset = {1, 3, 5, 7, 13, 14, 15, 18, 22, 24, 28, 29, 30}
32 bit is false

结果是完全不同且奇怪的位顺序!

01010101 00000111 00100010 1000111

我做错了什么?

如何正确判断十六进制字符串中是否设置了某个位?

最佳答案

我很快地将其组合在一起:该解决方案不会首先将整个字符串转换为数字,而是在检查位之前尝试挑选出正确的字符:

public class Test {

public static void main(String[] args) {
for (int i = 0; i < 16; i++) {
test("DEAD", i);
}
}

public static boolean isBitSet(String hex, int bit) {
int n = bit >> 2;
int last = hex.length() - 1;
if (n < 0 || n > last) return false;
char c = hex.charAt(last - n);
int v = Integer.parseInt(Character.toString(c), 16);
int mask = 1 << (bit & 3);
return (v & mask) != 0;
}

public static void test(String hex, int bit) {
boolean set = isBitSet(hex, bit);
System.out.format("%s, bit %2d, %s%n", hex, bit, set ? "set" : "not set");
}

}

输出:

DEAD, bit  0, set
DEAD, bit 1, not set
DEAD, bit 2, set
DEAD, bit 3, set
DEAD, bit 4, not set
DEAD, bit 5, set
DEAD, bit 6, not set
DEAD, bit 7, set
DEAD, bit 8, not set
DEAD, bit 9, set
DEAD, bit 10, set
DEAD, bit 11, set
DEAD, bit 12, set
DEAD, bit 13, not set
DEAD, bit 14, set
DEAD, bit 15, set

关于java - 如何确定十六进制字符串中是否设置了某个位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60074338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com