添加仅使用位运算符两个整数?

编程入门 行业动态 更新时间:2024-10-25 10:33:56
本文介绍了添加仅使用位运算符两个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在C#中,是不是可以不使用像IFS的事情进行两个32位整数的和,别人的,循环等?

In C#, is it possible to perform a sum of two 32-bit integers without using things like ifs, elses, loops etc?

也就是说,它可以只用按位操作或完成,并且,异或,非,左移和右移?

That is, can it be done using only the bitwise operations OR, AND, XOR, NOT, shift left and shift right?

推荐答案

下面是您娱乐的例子

unsigned int myAdd(unsigned int a, unsigned int b) { unsigned int carry = a & b; unsigned int result = a ^ b; while(carry != 0) { unsigned int shiftedcarry = carry << 1; carry = result & shiftedcarry; result ^= shiftedcarry; } return result; }

循环可以展开。它的执行次数,取决于操作数设置的位数,但它从来没有超过 unsigned int类型的宽度。一旦执行变为 0 ,接下来的迭代不会改变任何东西。

The loop could be unrolled. Number of times it executes, depends on the number of bits set in operands, but it's never greater than the width of unsigned int. Once carry becomes 0, next iterations don't change anything.

更多推荐

添加仅使用位运算符两个整数?

本文发布于:2023-11-30 01:37:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648286.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   运算符   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!