如何正确加减128位数字(如两个uint64_t)? [英] How to properly add/subtract a 128-bit number (as two uint64_t)?

查看:100
本文介绍了如何正确加减128位数字(如两个uint64_t)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C语言中工作,需要添加和减去一个64位数字和一个128位数字.结果将保存在128位数字中.我正在使用一个整数数组来存储128位数字的上半部分和下半部分(即 uint64_t bigNum [2] ,其中 bigNum [0] 的重要性最低)).

I'm working in C and need to add and subtract a 64-bit number and a 128-bit number. The result will be held in the 128-bit number. I am using an integer array to store the upper and lower halves of the 128-bit number (i.e. uint64_t bigNum[2], where bigNum[0] is the least significant).

任何人都可以使用bigNum并向其中添加/减去 uint64_t 的加减函数吗?

Can anybody help with an addition and subtraction function that can take in bigNum and add/subtract a uint64_t to it?

我在网络上看到了许多不正确的示例,因此请考虑以下问题:

I have seen many incorrect examples on the web, so consider this:

bigNum[0] = 0;  
bigNum[1] = 1;  
subtract(&bigNum, 1);

此时, bigNum [0] 应该设置为所有位,而 bigNum [1] 则应该设置为无位.

At this point bigNum[0] should have all bits set, while bigNum[1] should have no bits set.

推荐答案

在1年级或2年级,您应该学习如何将1和10的加法分解成多个单独的加法十个单位.处理大数时,可以将相同的原理应用于任意大数的算术运算,方法是实现您的单位现在是2 ^位的单位,十"是大2 ^位,依此类推.

In grade 1 or 2, you should have learn't how to break down the addition of 1 and 10 into parts, by splitting it into multiple separate additions of tens and units. When dealing with big numbers, the same principals can be applied to compute arithmetic operations on arbitrarily large numbers, by realizing your units are now units of 2^bits, your "tens" are 2^bits larger and so on.

这篇关于如何正确加减128位数字(如两个uint64_t)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆