简体   繁体   中英

How to do math with a number represented as an array in C?

I have some unsigned char array. I want to represent a big number and add a number to this big number.

So for example I have these six elements:

0x00, 0x00, 0x00, 0x00, 0x00, 0xdf

I want to add 0x11 and get

0x00, 0x00, 0x00, 0x00, 0x00, 0xf0

So, if I add 0x10 after, I should have

0x00, 0x00, 0x00, 0x01, 0x00

Could I do it with binary operations or something another but without loops? My array could be much larger than six elements.

You sum each pair of bytes from the source arrays and if the result is larger then 0xFF you carry 1 to the next byte. A loop is required.

//Adds B to A, Len is the amount of bytes that will be added.
//Make sure that Len <= size of A
void Add(unsigned char *A, unsigned char *B, int Len)
{
    int Carry = 0;

    //Work backwards because the high byte of your array holds the least significant byte.
    for (int i = Len - 1; i >= 0; i--)
    {
        int Temp = (int) A[i] + B[i];   
        A[i] = (Temp + Carry) & 0xFF;
        if ((Temp + Carry) > 0xFF)
            Carry = 1;
        else
            Carry = 0;
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM