使用按位运算符算术运算符 [英] Arithmetic operators using bitwise operators
问题描述
有没有执行加法(或算术运算)通过的仅位运算符的方法吗?
Is there a way to perform addition(or arithmetic operations) by using ONLY bitwise operators?
推荐答案
的加成位的A,B和C
carry_out = b&c|a&b|a&c; // there's a carry, if at least 2 bits are set
sum = a^b^c; // the sum is the number of set bits modulo 2
一个人必须执行此在字中的所有位 - 使用carry_in = C = 0,迭代到carry_in(next_bit)= carry_out(previous_result)首先为0位。
One has to perform this for all bits in the word - first for bit 0 using carry_in = c = 0, and iterating to carry_in(next_bit) = carry_out(previous_result).
减法情况与比特反转的乙的距离的(A-B)的和初始利差设置为1。
Subtraction happens with bit inverting b from (a-b) and setting the initial carry to 1.
然而,如果一个人有在平行添加例如32号,可以适合'一'具有32个LSB所有这些数字的和并行地执行的二进制运算。这是一种被称为的位分片的
However, if one has to add e.g 32 numbers in parallel, one can fit 'a' with 32 lsbs of all those numbers and perform the binary operations in parallel. This is a technique called bit slicing.
有关乘法CSA(进位加法器保存绝对是最好的软件的方法 - 它具有最小的区域)
For multiplication CSA (carry save adder is definitely the best software approach -- it has the smallest "area")
作为练习,这里有一个计算的算法A + B(+ C)并行:
As an exercise, here's an algorithm that calculates a+b(+c) in parallel:
int a = 13113;
int b = 43334;
int c = 1;
int main()
{
int sum=a^b^c,c2;
c=((c&a)|(a&b)|(c&b))<<1;
while (c) {
c2=(c&sum)<<1;
sum^=c;
c=c2;
}
printf("%d\n",sum);
}
这篇关于使用按位运算符算术运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!