整数到二进制数组 [英] Integer to binary array

查看:41
本文介绍了整数到二进制数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将整数转换为 7 位布尔二进制数组.到目前为止,代码不起作用:如果我输入要转换的整数 8,而不是 0001000,我得到 1000000,或者说 15 我应该得到 0001111 但我得到 1111000.char 数组与二进制数组的长度不同,位置错误.

I'm trying to convert an integer to a 7 bit Boolean binary array. So far the code doesn't work: If i input say integer 8 to be converted, instead of 0001000 I get 1000000, or say 15 I should get 0001111 but I get 1111000. The char array is a different length to the binary array and the positions are wrong.

public static void main(String[] args){

    String maxAmpStr = Integer.toBinaryString(8);
    char[] arr = maxAmpStr.toCharArray();
    boolean[] binaryarray = new boolean[7];
    for (int i=0; i<maxAmpStr.length(); i++){
        if (arr[i] == '1'){             
            binaryarray[i] = true;  
        }
        else if (arr[i] == '0'){
            binaryarray[i] = false; 
        }
    }

    System.out.println(maxAmpStr);
    System.out.println(binaryarray[0]);
    System.out.println(binaryarray[1]);
    System.out.println(binaryarray[2]);
    System.out.println(binaryarray[3]);
    System.out.println(binaryarray[4]);
    System.out.println(binaryarray[5]);
    System.out.println(binaryarray[6]);
}

感谢任何帮助.

推荐答案

确实没有必要为此处理字符串,只需对您感兴趣的 7 位进行按位比较即可.

There's really no need to deal with strings for this, just do bitwise comparisons for the 7 bits you're interested in.

public static void main(String[] args) {

    int input = 15;

    boolean[] bits = new boolean[7];
    for (int i = 6; i >= 0; i--) {
        bits[i] = (input & (1 << i)) != 0;
    }

    System.out.println(input + " = " + Arrays.toString(bits));
}

这篇关于整数到二进制数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆