Implementation of +,-,*,/ with bitwise operator

There is a question asked on Stackoverflow : Divide a number by 3 without using *,/,+,-,% operators. This question is an Oracle interview question. Some people give excellent answers. You can go there and take a look. Usually we need to use bitwise operators to do this kind of implementations. Here I want to show you ways to implement +,-,*,/ with bitwise operators.

A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations. On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition. While modern high-performance processors usually perform addition and multiplication as fast as bitwise operations the latter may still be optimal for overall power/performance due to lower resource use. Some bitwise operators used frequently are <<(left shift),>>(right shift),~(complement),^(xor).


Come back to the implementation:


1. Add

int add(int x,int y){
    int a,b;
    do{
        a=x&y;
        b=x^y;
        x=a<<1;
        y=b;
    }while(a);
    return b;
}

The positions that generate a carry and the positions that don’t generate a carry. In each run, the newly generated carrys will be added to the corresponding positions.

2. Subtraction

int negate(int x){
    return add(~x,1);
}
 
int sub(int x,int y){
    return add(x,negate(y));
}

We can use the addition function implemented above here, first we implement how to get a negative number of a positive number. The ~x is to get the 1's complement of x and then by adding 1, we get the 2's complement number. This number will be the negative number of x.

Ok, then substration is just a number adds another number's negative number.

3. Multiplication

int mul(int x, int y){
    int m=1, z =0;
    if(x<0){
        x=negate(x);
        y=negate(y);
    }
 
    while(x>=m && y) {
        if (x &m) z=add(y,z);
        y <<= 1; m<<= 1;
    }
    return z;
}


The detail explanation for this implementation can be found in :Adding Two Numbers With Bitwise and Shift Operators. Here if x<0, we need to convert it to a positive number, otherwise, the result will be 0.

4. Division

int divide(int x,int y){
    int c=0,sign=0;
 
    if(x<0){
        x=negate(x);
        sign^=1;
    }
     
    if(y<0){
        y=negate(y);
        sign^=1;
    }
 
    if(y!=0){
        while(x>=y){
            x=sub(x,y);
            ++c;
        }
    }
    if(sign){
        c=negate(c);
    }
    return c;
}

If both x and y are positive numbers, then we will going to a while loop. Basically, what the loop does is to subtract y from x if x>=y, the loop will end until x

Note : The addition and multiplication implementations are from : Adding Two Numbers With Bitwise and Shift Operators.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
《Thinking in Java》是由Bruce Eckel撰写的一本Java编程的经典教材,该书以英文语言出版。以下是该书的目录大纲: Chapter 1: Introduction to Objects - Introduction - The progress of abstraction - How objects communicate - Every object has an interface - The process of object-oriented design - Implementation hiding - Inheritance and reuse - Polymorphism and dynamic binding - Summary of object-oriented principles Chapter 2: Everything Is an Object - Primitive types - How the objects are created - Aliasing: All arguments are passed by value - Documentation comments - Controlling access to members of a class - First exposure to Java syntax Chapter 3: Operators - Thinking recursively - Operator precedence - Assignment with objects - Mathematical operators and precedence - Autoboxing and unboxing - Increment and decrement - Java logic operators - Bitwise operators - The instanceof operator - Summary of operators Chapter 4: Control Structures: Part 1 - True and false - The if-else statement - The switch statement - The while statement - The do-while statement - The for statement - Summary of control structures Chapter 5: Control Structures: Part 2 - The break and continue keywords - Foreach and multidimensional arrays - Using the comma operator - The return keyword - Summary of control structures Chapter 6: Initialization & Cleanup - Member initialization - Constructor initialization - Method overloading & generic methods - Order of initialization - Constructor & parameter lists - Garbage collection - The finalize() method - Summary of initialization and cleanup ......(接下去的章节继续)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值