Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to binary array

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

Any help is appreciated.

like image 680
David Flanagan Avatar asked Nov 16 '11 12:11

David Flanagan


6 Answers

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));
}
like image 161
ptomli Avatar answered Oct 11 '22 16:10

ptomli


I would use this:

private static boolean[] toBinary(int number, int base) {
    final boolean[] ret = new boolean[base];
    for (int i = 0; i < base; i++) {
        ret[base - 1 - i] = (1 << i & number) != 0;
    }
    return ret;
}

number 15 with base 7 will produce {false, false, false, true, true, true, true} = 0001111b

number 8, base 7 {false, false, false, true, false, false, false} = 0001000b

like image 33
Milbor Avatar answered Oct 11 '22 14:10

Milbor


What you get when you do System.out.println(maxAmpStr); is "1000" in case of the 8. So, you only get the relevant part, the first "0000" that you expected is just ommitted.

It's not pretty but what you could do is:

for (int i=0; i<maxAmpStr.length(); i++)
{
    if (arr[i] == '1')
    {
        binaryarray[i+maxAmpStr.length()-1] = true;
    }
    else if (arr[i] == '0')
    {
        binaryarray[i+maxAmpStr.length()-1] = false;
    }
}
like image 28
Fritz Avatar answered Oct 11 '22 16:10

Fritz


Hints: Think about what happens when you get a character representation that's less than seven characters.

In particular, think about how the char[] and boolean[] arrays "line up"; there will be extra elements in one than the other, so how should the indices coincide?


Actual answer: At the moment you're using the first element of the character array as the first element of the boolean array, which is only correct when you're using a seven-character string. In fact, you want the last elements of the arrays to coincide (so that the zeros are padded at the front not at the end).

One way to approach this problem would be to play around with the indices within the loop (e.g. work out the size difference and modify binaryarray[i + offset] instead). But an even simpler solution is just to left pad the string with zeros after the first line, to ensure it's exactly seven characters before converting it to the char array.

(Extra marks: what do you do when there's more than 7 characters in the array, e.g. if someone passes in 200 as an argument? Based on both solutions above you should be able to detect this case easily and handle it specifically.)

like image 22
Andrzej Doyle Avatar answered Oct 11 '22 15:10

Andrzej Doyle


Since nobody here has a answer with a dynamic array length, here is my solution:

public static boolean[] convertToBinary(int number) {
    int binExpo = 0;
    int bin = 1;
    while(bin < number) { //calculates the needed digits
        bin = bin*2;
        binExpo++;
    }
    bin = bin/2;
    boolean[] binary = new boolean[binExpo]; //array with the right length
    binExpo--;
    while(binExpo>=0) {
        if(bin<=number) {
            binary[binExpo] = true;
            number =number -bin;
            bin = bin/2;
        }else {
            binary[binExpo] = false;
        }
        binExpo--;
    }
    return binary;
}
like image 23
Nijco Avatar answered Oct 11 '22 14:10

Nijco


The char-array is only as long as needed, so your boolean-array might be longer and places the bits at the wrong position. So start from behind, and when your char-array is finished, fill your boolean-array with 0's until first position.

like image 29
SpeziFish Avatar answered Oct 11 '22 14:10

SpeziFish