-
请用自己熟悉的语言,实现无符号大数加法操作。
a. 完成两个大数的加法 A + B = C,并正确处理进位情况;
b. 成功返回0,失败返回-1
c. 各个大数用无符号字节数组表示。
d. C语言接口说明如下
int bignum_add(uint8_t* pA, int aLen, uint8_t* pB, int bLen, uint8_t* pC, int* cLen);举例:
uint8_t A[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x22, 0x33, 0x44};
uint8_t B[] = {0x33, 0x44};
//结果输出为: {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x22, 0x66, 0x88}
/*************************************************************************
> File Name: integer_add.c
> Author: killshadow
> Mail: chaceli@foxmail.com
> Created Time: 2021-8-4
************************************************************************/
#include <stdio.h>
#include <stdint.h>
#define MAX_LEN 100
/**
* Add big num function.
*
* @param pA first big num.
* @param aLen first big num len.
* @param pB second big num.
* @param bLen second big num len.
* @param pC calculate result big num.
* @param cLen calculate result big num len.
* @return {@code 0} calculate success.
*/
int bignum_add(uint8_t* pA, int aLen, uint8_t* pB, int bLen, uint8_t* pC, int* cLen);
/**
* Print byte array.
*
* @param arr
* @param length
*/
void print_arr(uint8_t *arr, int length);
/**
* Reverse array
* @param arr input array.
* @param length input array len.
*/
void reverse_arr(uint8_t* arr, int length);
/**
* Fill array with 0xFF by start index.
* @param arr input array.
* @param start start index.
* @param length array length.
*/
void fill_arr(uint8_t* arr, int start, int length);
int bignum_add(uint8_t* pA, int aLen, uint8_t* pB, int bLen, uint8_t* pC, int* cLen)
{
if ((pA == NULL) || (aLen <= 0) || (pB == NULL) || (bLen <= 0) || (pC == NULL)) {
return -1;
}
int carry = 0;
int tmp;
int idx;
int long_len;
int short_len;
if (aLen >= bLen) {
long_len = aLen;
short_len = bLen;
} else {
long_len = bLen;
short_len = aLen;
}
reverse_arr(pA, aLen);
reverse_arr(pB, bLen);
for (idx = 0; idx < short_len; idx++) {
tmp = pA[idx] + pB[idx] + carry;
pC[idx] = tmp % 0xFF;
carry = tmp / 0xFF;
}
if (carry != 0) {
pC[idx] = carry;
*cLen = long_len + 1;
} else {
*cLen = long_len;
}
return 0;
}
void print_arr(uint8_t *arr, int length) {
for (int i = length - 1; i >= 0; i--) {
printf("0x%x ", arr[i]);
}
puts("\n");
}
void reverse_arr(uint8_t *arr, int length) {
int left = 0;
int right = length - 1;
while (left < right) {
int tmp = arr[right];
arr[right--] = arr[left];
arr[left++] = tmp;
}
}
void fill_arr(uint8_t* arr, int start, int length)
{
for (int i = start; i < length; ++i) {
arr[i] = 0xFF;
}
}
int main()
{
uint8_t A[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x22, 0x33, 0x44};
int aLen = sizeof(A) / sizeof(uint8_t);
uint8_t B[] = {0x33, 0x44};
int bLen = sizeof(B) / sizeof(uint8_t);
// {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x22, 0x66, 0x88}
uint8_t C[MAX_LEN] = {0xFF};
fill_arr(C, 0, MAX_LEN);
int cLen = 0;
bignum_add(A, aLen, B, bLen, C, &cLen);
print_arr(C, cLen);
return 0;
}