java - 在java中改变一个字节内的一位

标签 java bit-manipulation

所以我了解如何更改一个字节中的单个位,但我不确定为什么我的特定代码不起作用。

public static void setBit(byte[] input, int position, int value) {
    int byteLocation = position / 8;
    int bitLocation = position % 8;
    byte tempByte = input[byteLocation];

    if (value == 0) 
    tempByte = (byte) (tempByte & ~(1 << bitLocation));
    else
    tempByte = (byte) (tempByte | (1 << bitLocation));

    input[byteLocation] = tempByte;
}

现在我一直在用 64 位长的字符串“Testing1”对其进行测试,然后尝试设置位并显示值。它最多可以处理 46 位,然后在第 47 位上,如果我尝试将其设置为 1,它就会出错,但是可以正常使用 0。

在我的方式中看不到错误,这是我正在测试的方式

String test = "Testing1";

byte[] bytes = test.getBytes();

for (int i = 0; i < bytes.length; i++)
    System.out.print(String.format("%8s", Integer.toBinaryString(bytes[i])).replace(' ', '0') + "[" + i + "] ");

setBit(bytes, 44, 1);
System.out.println();
for (int i = 0; i < bytes.length; i++)
    System.out.print(String.format("%8s", Integer.toBinaryString(bytes[i])).replace(' ', '0') + "[" + i + "] ");

以下是我尝试将第 47 位更改为 1 时的输出

01010100[0] 01100101[1] 01110011[2] 01110100[3] 01101001[4] 01101110[5] 01100111[6] 00110001[7] 
01010100[0] 01100101[1] 01110011[2] 01110100[3] 01101001[4] 11111111111111111111111111101110[5] 01100111[6] 00110001[7] 

最佳答案

将格式更改为

Integer.toBinaryString(0xFF & bytes[i])

byte 需要被屏蔽掉,因为它是符号扩展的,而不是零扩展的,到 32 位 int

关于java - 在java中改变一个字节内的一位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15916793/

相关文章:

c++ - 将 3 个 float 压缩为一个 uint64_t

php - 了解 PHP &(与号,按位与)运算符

c - 将 64 位十六进制地址中的位提取到 C 中的无符号整数中

java - 字符串比较中的空指针异常

java - Android 像 C++ 中的内联汇编一样运行 Dalvik 字节码

java - ActionListener 从 Jpanel 调用另一个 Jpanel

c++ - 如何将 4 个 2 位值合并为 1 个 8 位值?

java - 在viewpager中单击时如何在新 Activity 中打开图像?

java - 在 GUI 构建器中重新验证 JPanel

java - 按位加法在 Java 上有效,但在 Ruby 上失败