Divide two integers using only bitwise operations [duplicate]

风格不统一 提交于 2020-01-16 08:24:31

问题


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);

回答1:


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?



来源:https://stackoverflow.com/questions/12539877/divide-two-integers-using-only-bitwise-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!