Divide two integers using only bitwise operations

2019-08-17 05:09发布

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条回答
狗以群分
2楼-- · 2019-08-17 05:53

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?

查看更多
登录 后发表回答