Adding 1 to binary byte array

梦想的初衷 提交于 2020-08-04 19:43:09

问题


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;

  }

回答1:


The idea:

100010001 +       1000000 +          1111111 +
        1 =             1 =                1 =
---------         -------            -------
100010010         1000001         (1)0000000

I designed the operation as you can do on paper.

As for decimal operation adding a number is done starting from right (less significant digit) to left (most significant digit).

Note that 0 + 1 = 1 and I finished so I can exit

Instead 1 + 1 = 10 (in binary) so I write 0 (at the rightest position) and I have a remainder of 1 to add to next digit. So I move left of one position and I redo the same operation.

I hope this is helpful to understand it


It is a simple algorithm:

  • Set position to the last byte.
  • If current byte is 0 change it to 1 and exit.
  • If current byte is 1 change it to 0 and move left of one position.

    public static byte[] addOne(byte[] A) {
        int lastPosition = A.length - 1; 
    
        // Looping from right to left
        for (int i = lastPostion; i >= 0; i--) {
            if (A[i] == 0) {
                A[i] = 1; // If current digit is 0 I change it to 1
                return A; // I can exit because I have no reminder
            }
            A[i] = 0;     // If current digit is 1 I change it to 0 
                          // and go to the next position (one position left)
        }
        return A;         // I return the modified array
    }
    

If the starting array is [1,0,1,1,1,1,1,0,0] the resulting array will be [1,0,1,1,1,1,1,0,1].

If the starting array is [1,0,1,1,1,1,1,1,1] the resulting array will be [1,1,0,0,0,0,0,0,0].

If the starting array is [1,1,1,1,1,1,1,1,1] the resulting array will be [0,0,0,0,0,0,0,0,0].

Note If you need to handle this last situation (overflow) in a different manner you can try one of the following:

  • throw an exception
  • enlarge the array of 1 and result [1,0,0,0,0,0,0,0,0,0]

Here is a piece of code to handle both situations:

Throwing exception:

    public static byte[] addOne(byte[] A) throws Exception {
        for (int i = A.length - 1; i >= 0; i--) {
            if (A[i] == 0) {
                A[i] = 1;
                return A;
            }
            A[i] = 0;
            if (i == 0) {
                throw new Exception("Overflow");
            }
        }
        return A;
    }

Enlarging array:

    public static byte[] addOne(byte[] A) {
        for (int i = A.length - 1; i >= 0; i--) {
            if (A[i] == 0) {
                A[i] = 1;
                return A;
            }
            A[i] = 0;
            if (i == 0) {
                A = new byte[A.length + 1];
                Arrays.fill(A, (byte) 0); // Added cast to byte
                A[0] = 1;
            }
        }
        return A;
    }



回答2:


I suspect it works in some cases but not other as your code is too complicated.

static byte[] increment(byte[] bits) {
    byte[] ret = new byte[bytes.length+1];
    int carry = 1, i = 0;
    for(byte b: bits) {
       // low bit of an add;
       ret[i++] = b ^ carry;
       // high bit of an add.
       carry &= b;
    }
    if (carry == 0)
       return Arrays.copyOf(ret, bytes.length);
    ret[i] = 1;
    return ret;
}



回答3:


For an array bits containing the binary numbers, the algorithm for adding 1 is:

Boolean carried = true;
for(int i = bits.length-1; i>=0; i--) {
  if(bits[i] == 1 && carried) {
    carried = true;
    bits[i] = 0;
  }
  else if (bits[i] == 0 && carried) {
    carried = false;
    bits[i] = 1;
  }
{

if(carried)
  throw new Exception("Overflow");


来源:https://stackoverflow.com/questions/32253298/adding-1-to-binary-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!