0

For this exercise I'm making I want a decimal < 4096 to be written in binary form in an int array.

So for example, 4 would be {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:

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:

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?

1

7 Answers 7

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

This isn't quite right as in the example the highest bit comes first where as your code would put it last.
Ah, the teacher hinted to this indeed, but I didn't realize how easy it can be. Thanks!
@nickt but that is just a simple addition. This is for the whole exercise a more elegant way.
@Niek: If this is homework-related, will you please tag it as such?
Yes you just need to reverse the order. I did give the correct answer below but my tablet messed up the formatting. :-(
|
0

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'.

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;
}

Comments

0
String s = Integer.toBinaryString(int value);

Now convert the String to int[]

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

Comments

0

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';
    }

Comments

0

"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. 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.

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.

Comments

0
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;
}

Comments

0

You could use the bit shift operator together withbthe bitwise AND operator as follows. Note bitCount - i - 1 is needed to get the high bit first.

    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;
    }

3 Comments

Thanks! :-) The formatting doesn't seem to work on my tablet.
All you needed was an empty line between your paragraph and the code.
@StriplingWarrior Thanks I will try that next time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.