17

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.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
David Flanagan
  • 373
  • 2
  • 7
  • 19
  • 1
    Is it homework? Use division and remainder by 2. – kan Nov 16 '11 at 12:12
  • Have you tried walking through your code, either by hand or using a debugger? Neither should be a challenge if you use `8` as the input, and will let you see where your result starts to deviate from being correct. – Andrzej Doyle Nov 16 '11 at 12:13

11 Answers11

39

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));
}
ptomli
  • 11,730
  • 4
  • 40
  • 68
  • 4
    +1 for being such a concise example but your answer could do with an explanation for why the OP's doesn't work. – Radiodef Nov 07 '13 at 05:29
  • Well I am interested in 200+ `bits` so this solution does not work. Can you give an advice ? Is there a way to work with `boolean[]` (`bits`) or should I try `Strings` ? – Lazar Lazarov Nov 21 '16 at 14:51
15

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

Milbor
  • 151
  • 1
  • 4
  • 6
    The usage of `base` here is a bit misleading, since binary is always base 2. Perhaps `length` would be more appropriate. In fact, you can compute `length` as the ceiled base-2 logarithm of `number`. – Martijn Mar 28 '16 at 14:39
3

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

Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
3

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;
    }
}
eeerahul
  • 1,629
  • 4
  • 27
  • 38
Fritz
  • 186
  • 2
2

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;
}
Nijco
  • 21
  • 4
  • 1
    What about using this to find out the size of the array of bits: ⌊log2(n)⌋ + 1, where ⌊x⌋ is the floor of x. - https://www.exploringbinary.com/number-of-bits-in-a-decimal-integer/ – Enrico Giurin Apr 24 '19 at 01:49
1

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.

SpeziFish
  • 3,262
  • 2
  • 28
  • 27
0
  public static boolean[] convertToBinary(int b){
    boolean[] binArray = new boolean[7];
    boolean bin;
    for(int i = 6; i >= 0; i--) {
      if (b%2 == 1) bin = true;
      else bin = false;
      binArray[i] = bin;
      b/=2;
    }
    return binArray;
  }
Warren
  • 1
  • 1
0

Integer.toBinaryString(int i) does not pad. For e.g. Integer.toBinaryString(7) prints 111 not 00000111 as you expect. You need to take this into account when deciding where to start populating your boolean array.

mcfinnigan
  • 11,442
  • 35
  • 28
  • Even if `toBinaryString` printed `00000111`, this program would still be incorrect as the indices would still not "line up" between the char and boolean arrays. (In fact it would fail with an IndexOutOfBoundsException, though that could be trivially fixed to leave the underlying issue.) – Andrzej Doyle Nov 16 '11 at 12:29
0

15.ToBinaryString will be '1111'

You are lopping through that from first to last character, so the first '1' which is bit(3) is going into binaryArray[0] which I'm assuming should be bit 0.

You ned to pad ToBinaryString with leading zeros to a length of 7 (8 ??) and then reverse the string, (or your loop)

Or you could stop messing about with strings and simply use bit wise operators

BinaryArray[3] = (SomeInt && 2^3 != 0);

^ = power operator or if not (1 << 3) or whatever is left shift in Java.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
-1
    public static String intToBinary(int num) {
    int copy = num;
    String sb = "";
    for(int i=30; i>=0; i--) {
        sb = (copy&1) + sb;
        copy = copy >>>=1;
    }
    return sb;
}
  1. AND the number with 1
  2. Append the vale to a string
  3. do unsigned right shift repeat steps 1-3 for i=30..0
Jeya
  • 117
  • 1
  • 2
-1
String maxAmpStr = Integer.toBinaryString(255);
    char[] arr = maxAmpStr.toCharArray();
    boolean[] binaryarray = new boolean[20];
    int pivot = binaryarray.length - arr.length;
    int j = binaryarray.length - 1;
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] == '1') {
            binaryarray[j] = true;
        } else if (arr[i] == '0') {
            binaryarray[j] = false;
        }
        if (j >= pivot)
            j--;
    }

    System.out.println(maxAmpStr);
    for (int k = 0; k < binaryarray.length; k++)
        System.out.println(binaryarray[k]);
}
  • 1
    it will be nice if you can elaborate further of what that code snippets all about, that would lead to better understanding for future viewers. – Roy Lee Mar 25 '15 at 10:45