16

If I have a binary notation such as "1000010" which equals 66 and I want to increment it by one to "1000011" which equals 67. How is that done correctly in my array? Currently it's printing out "0100010" which is 34, but no where near the correct answer. I don't think my array is shifting correctly, nor will it increase size as the numbers get larger. Although, I can't make any assumptions about how big the array can be other than what's explicitly stated.

public class math {


//=================================================================
  // increment(A) returns an array of bits representing A+1.
  //=================================================================

  public static byte[] increment(byte[] A)
  {
    byte carry= 1;
    for(int i = 0; i<A.length; i++){
        byte b = A[i];
        A [i] ^= carry;
         carry &= b;
    }
    return A;
  }

  private static String toBinString (byte [] a) 
  {
      String res = "";
      for (int i = 0; i <a. length; i++) 
      {
          res = (a [i] == 0 ? "0": "1") + res;
      }
      return res;
}


/**
 * @param args
 */
public static void main(String[] args) {
         byte [] A ={1,0,0,0,0,1,0};

         increment(A);
             System.out.println (toBinString (A));


}
 }
Bill the Lizard
  • 369,957
  • 201
  • 546
  • 842
r2thek
  • 161
  • 1
  • 3
  • related: http://stackoverflow.com/questions/1034473/java-iterate-bits-in-byte-array –  Sep 07 '11 at 00:25
  • 3
    In your declaration of A it looks like you want the leftmost (first) array be the most significant bit, in the rest of your program you consider the first element of the array as the least significant bit. Easiest solution would probably be to enter your number in reverse order in the array, or inverse the array... – fvu Sep 07 '11 at 00:27
  • This solution worked for me: https://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java – HoldOffHunger Jun 07 '17 at 00:29

6 Answers6

5

The lazy (and secure) way for increment by one :

    String s = "1000010";
    for (int i = 0; i < 5; i++) {
        System.out.print(s);
        System.out.println("\t" + Integer.valueOf(s, 2));
        s = Integer.toBinaryString(Integer.valueOf(s, 2) + 1);
    }

Output :

1000010 66
1000011 67
1000100 68
1000101 69
1000110 70

(Edited for presentation)

cl-r
  • 1,234
  • 12
  • 24
  • This will not produce uniform results with variable-length binary numbers. I.E., 1 comes out as "1", 2 comes out as "10", 4 comes out as "100", etc.. It only works because of the specific numbers you're demonstrating here. – HoldOffHunger Jun 07 '17 at 00:28
4

This worked for me:

public static void main(String[] args) {
    byte [] A ={1,0,0,0,0,1,0};
    increment(A);
    System.out.println (toBinString (A));
}

public static byte[] increment(byte[] A) {
    boolean carry = true;
    for (int i = (A.length - 1); i >= 0; i--) {
        if (carry) {
            if (A[i] == 0) {
                A[i] = 1;
                carry = false;
            }
            else {
                A[i] = 0;
                carry = true;
            }
        }
    }

    return A;
}

private static String toBinString (byte [] a) {
      String res = "";
      for (int i = 0; i < a. length; i++) {
          res += (a [i] == 0 ? "0": "1") ;
      }
      return res;
}
Snowy Coder Girl
  • 5,162
  • 10
  • 36
  • 65
1
//Function call
incrementCtr(ctr, ctr.length - 1);

//Increments the last byte of the array
private static void incrementCtr(byte[] ctr, int index) {       

    ctr[index]++;

    //If byte = 0, it means I have a carry so I'll call 
    //function again with previous index
    if(ctr[index] == 0) {
        if(index != 0)
            incrementCtr(ctr, index - 1);
        else
            return;
    }
}
gssln
  • 11
  • 1
1

Late but concise:

public static void increment(byte[] a) {
    for (int i = a.length - 1; i >= 0; --i) {
        if (++a[i] != 0) {
            return a;
        }
    }
    throw new IllegalStateException("Counter overflow");
}
Christof R
  • 823
  • 5
  • 9
0
public static byte[] increment(byte[] array) {
    byte[] r = array.clone();
    for ( int i = array.length - 1; i >= 0; i-- ) {
        byte x = array[ i ];
        if ( x == -1 )
            continue;
        r[ i ] = (byte) (x + 1);
        Arrays.fill( r, i + 1, array.length, (byte) 0 );
        return r;
    }
    throw new IllegalArgumentException( Arrays.toString( array ) );
}

exception if overflow

terentev
  • 623
  • 1
  • 8
  • 10
0

In this case you can iterate on all values.

public boolean increment() {
    int i = this.byteArray.length;

    while (i-->0 && ++this.byteArray[i]==0);

    return i != -1;
}

At the end you can increase the array's size.

C Würtz
  • 708
  • 7
  • 20