简体   繁体   English

Java十进制到二进制int数组

[英]Java decimal to binary int array

For this exercise I'm making I want a decimal < 4096 to be written in binary form in an int array. 对于本练习,我想将一个<4096的十进制数以二进制形式写入int数组中。

So for example, 4 would be {0,0,0,0,0,0,0,0,0,1,0,0} . 因此,例如4将是{0,0,0,0,0,0,0,0,0,1,0,0} I need this for (nearly) all integers up to 4096, so I've written this piece of code: 我需要(几乎)所有最大为4096的整数,所以我编写了这段代码:

for(int k=0; k<4096; k++){
    int[] myNumber =  { (k / 2048) % 2, (k / 1024) % 2, (k / 512) % 2, (k / 256) % 2, (k / 128) % 2, (k / 64) % 2, (k / 32) % 2, (k / 16) % 2, (k / 8) % 2, (k / 4) % 2, (k / 2) % 2, (k / 1) % 2 }
    /* Some processing */
}

This looks kind of ugly, so that's why I'm curious to find out if there is a more elegant way of achieving this? 这看起来很难看,所以这就是为什么我想知道是否有更优雅的方法来实现这一目标?

For the interested reader: 对于感兴趣的读者:
I chose for the array approach of storing the binary numbers, because I need to perform some shifting and addition modulo 2. I'm using an LFSR, and this is my implementation for that: 我选择使用存储二进制数的数组方法,因为我需要执行一些移位和加法模2。我正在使用LFSR,这是我的实现:

public class LFSR {

    private int[] polynomial;

    public LFSR(int[] polynomial) {
        this.polynomial = polynomial;
    }

    public int[] shiftLeft(int[] input) {
        int[] result = new int[input.length];

        int out = input[0];
        result[input.length - 1] = out;
        for (int i = input.length - 1; i > 0; i--) {
            result[i - 1] = (input[i] + polynomial[i - 1] * out) % 2;
        }

        return result;
    }

}

Any suggestions? 有什么建议么?

Some pseudo code: 一些伪代码:

While (int i = 0; i < 12; i++) { 
   bitarray[i] = numericalValue & 0x1;
   numericalValue = numericalValue >> 1;
}

So, shifting right by one bit is division by 2, and ANDing with 1 always leaves you only with the lowest bit which is what you want. 因此,右移一位就是2除,与1的AND运算始终只会使您得到所需的最低位。

public int[] toBin (int num)
{
int[] ret = new int[8];
for (int i = 7, p = 0; i>=0; i--, p++)
{
ret[i] = (num/2**p) % 2;
}
return ret;
}

One quick suggestion would be to switch to a byte array instead of an int array, simply to save space, as they will only be 'bits'. 一个快速的建议是切换到字节数组而不是int数组,只是为了节省空间,因为它们只会是“位”。

With regards to improving the elegance of your solution, it is perhaps easier to use subcomputations: 关于改善解决方案的美观性,使用子计算也许更容易:

int[] intToBinaryArray(int dec){

int[] res = int[12]
for(int i =0; i < 12; i++)
    bitarray[i] = numericalValue & 0x1; //grab first bit only
    dec  /= 2;
}

return res;
}

"Elegance" is in the eye of the beholder, but I'd start by creating a method to avoid repetition and improve clarity: “优雅”在旁观者眼中,但是我将首先创建一种避免重复并提高清晰度的方法:

int[] myNumber =  { getBit(k, 12), getBit(k, 11), ... };

I personally feel this is the "most elegant" way to get a particular bit: 我个人觉得这是获取特定内容的“最优雅”方法:

int getBit(int v, int i)
{
    return v >> i & 1;
}

Then you have to decide whether you want to keep repeating yourself with the calls to getBit or whether you'd rather just use a single while or for loop to populate the whole array. 然后,您必须决定是否要继续对getBit重复操作,还是只想使用单个whilefor循环来填充整个数组。 You'd think it'd be quicker the way you've got it written, but there's good chance the JIT compiler automatically unrolls your loop for you if you use a loop like Jochen suggests. 您可能会认为编写起来会更快,但是如果您使用Jochen建议的循环,那么JIT编译器很有可能会自动为您展开循环。

Since this particular operation is entirely self contained, you might even want to create a special method for it: 由于此特定操作完全是自包含的,因此您甚至可能想要为其创建一个特殊方法:

int[] getBits(int v, int num)
{
    int[] arr = new int[num];
    for(int i=0; i<num; i++) {
        arr[i] = getBit(v, num - i - 1);
    }
    return arr;
}

That makes it easier to unit test, and you can reuse it in a variety of situations. 这使得单元测试更加容易,并且您可以在各种情况下重用它。

String s = Integer.toBinaryString(int value);

Now convert the String to int[] 现在将字符串转换为int []

int[] intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10);
}

This is somewhat shorter ;) 这有点短;)

    int[] bits = new int[13];
    String bin = Integer.toBinaryString(8192 + value);
    for(int i = 1; i < bin.length(); i++) {
        bits[i-1] = bin.charAt(i)-'0';
    }

You could use the bit shift operator together withbthe bitwise AND operator as follows. 您可以按如下方式将位移运算符与按位AND运算符一起使用。 Note bitCount - i - 1 is needed to get the high bit first. 注意bitCount-i-1需要首先获得高位。

    final int bitCount =12; // Increase to support greater than 4095
    int[] number = new int[bitCount];
    for( int i = 0; i < bitCount; i++ )
    {
      number[i] = ( k >>> ( bitCount - i - 1 ) ) & 1;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM