只使用位运算分为两个整数 [英] Divide two integers using only bitwise operations

查看:185
本文介绍了只使用位运算分为两个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/5284898/implement-division-with-bit-wise-operator\">implement师带逐位运算符


我最近买了更深入的由按位函数,并开始实施与位运算符基本算术运算。到目前为止,我已经得到了(+, - ,*)。不过,我真的不知道如何处理部门。我知道,我可以以某种方式用乘法来代替,但不知道如何使用该方法既可以解决这个。

那么,如何会只用按位运算符我实现除法的这些:(|,放大器;,〜,^,&GT&;&GT中,&lt;&LT;)用C ?对于任何人谁问,这是不是功课,只是个人的知识。

如果你愿意,你可以调用code以下功能,使其更容易(这是prewritten)

  INT BADD(INT N1,N2 INT);
INT bsub(INT N1,N2 INT);
INT bmult(INT N1,N2 INT);


解决方案

好了,你可以把两个整数不使用任何运营商都在C,假设你有可用的标准库:

  INT结果= DIV(A,B).quot;

<分> 注意:这个答案是纯粹的修辞,但它被放在那里显示试图用C来写,整个划分功能的愚蠢当标准库(和语言本身)有这方面的支持。为什么当答案已经在你的指尖,你会重新写轮(即使只是为了学习)?

Possible Duplicate:
implement division with bit wise operator

I recently got into more depth by bitwise functions, and started to implement basic arithmetic functions with bitwise operators. So far I have gotten (+, -, *). However I'm not really sure how to approach division. I know that I could somehow use multiplication instead, but not sure how to approach this using that method either.

So how would I implement division using only bitwise operators these: (|, &, ~, ^, >>, <<) in C? For anyone who asks, this is not homework, just personal knowledge.

If you like, you can call the following functions in the code to make it easier (These are prewritten)

int badd(int n1, int n2);
int bsub(int n1, int n2);
int bmult(int n1, int n2);

解决方案

Well, you can divide two integers without using any operators at all in C, assuming you have the standard library available:

int result = div(a, b).quot;

Note: this answer was purely rhetorical, but it was put out there to show the foolishness of attempting to write an entire dividing function in C, when the standard library (and the language itself) has support for it. Why would you re-write the wheel (even if just to learn) when the answer is already at your fingertips?

这篇关于只使用位运算分为两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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