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.

2
  • 1
    Is it homework? Use division and remainder by 2. Commented Nov 16, 2011 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. Commented Nov 16, 2011 at 12:13

11 Answers 11

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 for being such a concise example but your answer could do with an explanation for why the OP's doesn't work.
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 ?
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

1 Comment

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

Comments

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

Comments

3

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

2 Comments

What about using this to find out the size of the array of bits: ⌊log2(n)⌋ + 1, where ⌊x⌋ is the floor of x. - exploringbinary.com/number-of-bits-in-a-decimal-integer
The needed size is just 32 - Integer.numberOfLeadingZeros(value) but this code is unreliable anyway as doesn’t work when all 32 bits are used (because the value will be interpreted as negative).
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.

Comments

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.

1 Comment

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

2 Comments

Did you mean to say Integer.toBinaryString(15) ? If so would you mind editing this answer? That's a great way to do this.
Not a java guy, so I don't even know if you are right. Thought the idea was clear though.
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;
  }

1 Comment

This could be expanded to support all 32 bits when using (b&1) instead of b%1 and b>>>=1 instead of b/=2. Besides that there is no point in writing if(condition) variable = true; else variable = false; when you can write variable = condition; in the first place. Or even get rid of the obsolete bin variable and write binArray[i] = (b&1) != 0;
-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

Comments

-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 Comment

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.

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.