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