得到 unsigned long long 加法进位 [英] get unsigned long long addition carry

查看:69
本文介绍了得到 unsigned long long 加法进位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到在 c 中添加两个无符号 64 位整数的进位位.如果需要,我可以使用 x86-64 asm.代码:

I want to get the carry bit of adding two unsigned 64-bit integers in c. I can use x86-64 asm if needed. code:

#include <stdio.h>

typedef unsigned long long llu;

int main(void){
  llu a = -1, b = -1;
  int carry = /*carry of a+b*/;
  llu res = a+b;
  printf("a+b = %llu (because addition overflowed), carry bit = %d\n", res, carry);
  return 0;
}

推荐答案

As @EugeneSh.观察到,进位是 0 或 1.此外,鉴于 ab 都具有相同的 unsigned 类型,它们的和是明确定义的即使算术结果超出其类型的范围.而且,当发生溢出时,和的(C)结果将小于 ab ,否则更大,因此我们可以使用 C 关系运算的事实评估为 0 或 1 以将进位位表示为

As @EugeneSh. observes, the carry is either 0 or 1. Moreover, given that a and b both have the same unsigned type, their sum is well defined even if the arithmetic result exceeds the range of their type. Moreover, the (C) result of the sum will be less than both a and b when overflow occurs, and greater otherwise, so we can use the fact that C relational operations evaluate to either 0 or 1 to express the carry bit as

carry = (a + b) < a;

这不需要任何标题,也不依赖于特定的上限,甚至不依赖于具有相同类型的 ab.只要两者都具有无符号类型,它就会正确报告总和是否溢出其类型中的较宽者或 unsigned int(以较宽者为准),这与设置进位位的总和相同.作为奖励,它以总和本身表示,我认为这清楚地表明了正在测试的内容.

That does not require any headers, nor does it depend on a specific upper bound, or even on a and b having the same type. As long as both have unsigned types, it reports correctly on whether the sum overflows the wider of their types or unsigned int (whichever is wider), which is the same as their sum setting the carry bit. As a bonus, it is expressed in terms of the sum itself, which I think makes it clear what's being tested.

这篇关于得到 unsigned long long 加法进位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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