I am trying to add 1 to a byte array containing binary number. It works for some cases and not for others. I cannot convert my array to an integer and add one to it. I am trying to do the addition with the number in the array. If someone could please point me i where I am messing up on this!
Test cases that have worked: 1111, 0, 11
EDIT: I understand how to do it with everyone's help! I was wondering if the binary number had the least significant bit at the first position of the array.
Example: 1101 would be stored as [1,0,1,1]-how could I modify my code to account for that?
public static byte[] addOne(byte[] A)
{
//copy A into new array-size+1 in case of carry
byte[] copyA = new byte[A.length+1];
//array that returns if it is empty
byte [] copyB = new byte [1];
//copy A into new array with length+1
for(byte i =0; i <copyA.length&& i<A.length; i ++)
{
copyA[i]=A[i];
}
//if there is nothing in array: return 1;
if(copyA.length == 0)
{
//it will return 1 bc 0+1=1
copyB[0]=1;
return copyB;
}
//if first slot in array is 1(copyA) when you hit zero you dont have to carry anything. Go until you see zero
if(copyA[0] ==1 )
{
//loops through the copyA array to check if the position 0 is 1 or 0
for(byte i =0; i<copyA.length; i ++)
{
if(copyA[i] == 0)//if it hits 0
{
copyA[i]=1;//change to one
break;//break out of for loop
}
else{
copyA[i]=0;
}
}
return copyA;
}
else if (copyA[0]==0)
{
copyA[0]=1;
}
return copyA;
}
System.arraycopy(srcArray, srcPos, destArray, destPos, length)