Byte array multiplication

This is my code - its classic multiplication A * B = C

private static int MASK = 0x00ff;
public static int multiplication(byte[] A, byte[] B, byte[] R)
{
    byte n = 0;
    int bb;
    int sum = 0;
    int lenbyte = 0;

    for (int c = 0; c < R.Length; c++) //R set 0
    {
        R[c] = 0;
    }

    int j = B.Length - 1;
    int i = 0;

    do //cycles go throught bytes of B from LSB to MSB
    {
       bb = B[j] & MASK;
       if (bb != 0x00)
       {
          i = A.Length - 1;
          n = 0x00; //carry byte

          do //cycles throught bytes of A from LSB to MSB
          {
              sum = ((A[i] & MASK) * bb) + (R[i + j+1 ]&MASK) + (n & MASK);
              R[i + j+1] = (byte)(sum & MASK);
              n = (byte)((uint)sum >> 8);
              i--;
          } while (i >= 0);
          R[j] = n;
          j--;
       }
       else
       {
          R[j] = 0x00;
          j--;
       }
    } while (j >= 0);

    return 1;
}

This does not work well. I think the problem is beaten. Thank you for your ideas. :)

+3
source share
1 answer

As I understand it, your code takes A and B as input and returns the result in R on the right? Well, as you encoded it, it won’t work. You pass R as a parameter to the scope of the multiplication function. This means that after the function returns, all the memory used by this function will be freed and R will be cleared. You also use the parameter transfer parameter, which in C # makes a copy of the original parameter for use in the function and does not change the original variable.

, , :

public static int multiplication(byte[] A, byte[] B, ref byte[] R)
{
...

, :

public static byte[] multiplication(byte[] A, byte[] B)
{
byte[] R; // define this and give it the correct size

// add your code here

return R;
}
0

All Articles