I misunderstood a question that said to add two integers using bitwise operations. I did not use any control flow and could not do it. After giving up, all the solutions I found use control flow to accomplish this whether it be an if
, while
, for
, recursion, etc,. Is there a proof that is can\cannot be accomplished?
相关问题
- Index of single bit in long integer (in C) [duplic
- Logical vs. bitwise operator AND
- Cast some light on population count algorithm
- Can I reinterpret_cast the parameter of a constexp
- Bit shifting and bit mask - sample code
相关文章
- Construction an logical expression which will coun
- Rounded division by power of 2
- Compact a hex number
- One function with different arguments to push cert
- Unpacking a bitfield (Inverse of movmskb)
- Fastest way to count consecutive 1 bits. C++
- Create method which checks if x + y will overflow
- Bit manipulation, permutate bits
For a fixed length integer, you can just unroll a ripple carry adder. In the worst case, a carry signal has to propagate all the way from the least significant bit to the most significant bit.
Like this (only slightly tested) (to avoid the C-purists' wrath, I will call this C# code)
If you do it for as many bits as your integer will hold, you won't need the mask in the end.
That's not very efficient, clearly. For 3 bits it's fine, but for 32 bits it becomes quite long. A Kogge-Stone adder (one of the O(log n) delay adder circuits) is also surprisingly easy to implement in software (in hardware you have to deal with a lot of wires, software doesn't have that problem).
For example: (verified using my website)