Как правильно увеличивать биты в массиве?

Если у меня есть двоичная нотация, такая как "1000010", которая равна 66, и я хочу увеличить ее на единицу до "1000011", что равно 67. Как это сделано правильно в моем массиве? В настоящее время он распечатывает "0100010", который составляет 34, но не где рядом с правильным ответом. Я не думаю, что мой массив смещается правильно, и он не увеличит размер по мере увеличения числа. Хотя, я не могу делать никаких предположений о том, насколько большой может быть массив, чем явно указано.

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


}
 }

Ответы

Ответ 1

ленивый (и безопасный) способ для увеличения на единицу:

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

Выход:

1000010 66
1000011 67
1000100 68
1000101 69
1000110 70

(Отредактировано для презентации)

Ответ 2

Это сработало для меня:

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

Ответ 3

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

Ответ 4

Позднее, но краткое:

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

Ответ 5

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

исключение, если переполнение