簡體   English   中英

如何用C中表示為數組的數字進行數學運算?

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

我有一些unsigned char數組。 我想代表一個大數字,並在這個大數字上加一個數字。

例如,我有這六個元素:

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

我想添加0x11並得到

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

所以,如果我在之后添加0x10 ,我應該有

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

我可以用二元運算或其他但沒有循環的東西來做嗎? 我的數組可能比六個元素大得多。

您對源數組中的每對字節求和,如果結果大於 0xFF,則將 1 帶到下一個字節。 需要一個循環。

//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