java - 合并 char 数组会颠倒顺序

标签 java bit-manipulation

我编写了一个简单的程序来滑动整数(如 73)中的位位置。当我将数组转换回字符串时,位的顺序似乎颠倒了。我应该得到 11,我的答案是错误的 104。不知道我做错了什么。

public class P5_2 {


public static int myswap(int x, int i, int j)
{
    String xStr = Integer.toBinaryString(x);
    char[] arr = xStr.toCharArray();

    System.out.println(arr);

    char temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;


    xStr = new String(arr);

    //it seems it is joining the char array from LSB to MSB side, hence flipping !! why

    System.out.println(xStr);

    x = Integer.parseInt(xStr, 2);

    return x;


}

public static void main(String[] args)
{

    int x = 73;
    int n;
    int i = 6;
    int j = 1;

    n = myswap(x, i, j);


    System.out.print(n);
}
}

最佳答案

通常,二进制数表示中的位按从最低有效位到最高有效位的顺序从右到左编号。

例如二进制数字 73:

binary digits: 1 0 0 1 0 0 1
bit number:    6 5 4 3 2 1 0

但是,当您转换为二进制字符串(例如使用 toBinaryString())时,首先输出最高有效数字,因为字符串中的数字是从左到右存储的。例如字符串“10001001”:

char values: "1" "0" "0" "1" "0" "0" "1"
array index:  0   1   2   3   4   5   6

要交换原始数字的第 1 位和第 6 位,需要交换 char 数组的第 5 位和第 0 位元素。这将为您提供字符串“0001011”,解析为 11。交换元素 1 和 6 将获得字符串“1101000”,即 104。

所以你只需要根据字符串的长度反转索引的顺序:

String xStr = Integer.toBinaryString(x);
i = (xStr.length() - 1) - i;
j = (xStr.length() - 1) - j;

或者,如果您根本不想使用字符串,则可以使用 bit-manipulation 交换位。 :

public static int myswap(int x, int i, int j)
{
    // b is 1 if the bits are different (xor), 0 if not
    int b = ((x >> i) ^ (x >> j)) & 1;
    // flip the bits if they are different
    return x ^ ((b << i) | (b << j));
}

关于java - 合并 char 数组会颠倒顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37516941/

相关文章:

c - C 中的位计数类似于 bit twiddling hack

java - 继承:有没有办法发现调用方法的类?

java - SqlPagingQueryProviderFactoryBeanhaving 子句

java - 客户端拦截器和外部负载均衡架构

assembly - 使用按位运算将 Int 转换为 Float 或 Float 为 Int(软件浮点)

swift - 对范围内的值进行位操作

java - 遇到这个二次方程类JAVA的问题

java - TestNG 测试继承和组

Java 表达式等价

c - 7段LED + 4094