简体   繁体   English

如何用C中表示为数组的数字进行数学运算?

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

I have some unsigned char array.我有一些unsigned char数组。 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我想添加0x11并得到

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

So, if I add 0x10 after, I should have所以,如果我在之后添加0x10 ,我应该有

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.您对源数组中的每对字节求和,如果结果大于 0xFF,则将 1 带到下一个字节。 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;
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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