Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment bits correctly in an array?

Tags:

java

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


}
 }
like image 788
r2thek Avatar asked Sep 07 '11 00:09

r2thek


People also ask

How do you increment values in an array?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

What does ++ do to an array?

array[i]++ increments the value of array[i] . The expression evaluates to array[i] before it has been incremented. array[i++] increments the value of i . The expression evaluates to array[i] , before i has been incremented.

Can we increment the array?

No, it's not OK to increment an array. Although arrays are freely convertible to pointers, they are not pointers. Therefore, writing a++ will trigger an error.


1 Answers

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)

like image 90
cl-r Avatar answered Oct 15 '22 12:10

cl-r