Change sign using bitwise operators

How to change the sign of int using bitwise operators? Obviously we can use x*=-1 or x/=-1. Is there any fastest way of doing this?

I did a small test as below. Just for curiosity...

public class ChangeSign {
    public static void main(String[] args) {
        int x = 198347;
        int LOOP = 1000000;
        int y;
        long start = System.nanoTime();
        for (int i = 0; i < LOOP; i++) {
            y = (~x) + 1;
        }
        long mid1 = System.nanoTime();
        for (int i = 0; i < LOOP; i++) {
            y = -x;
        }
        long mid2 = System.nanoTime();
        for (int i = 0; i < LOOP; i++) {
            y = x * -1;
        }
        long mid3 = System.nanoTime();
        for (int i = 0; i < LOOP; i++) {
            y = x / -1;
        }
        long end = System.nanoTime();
        System.out.println(mid1 - start);
        System.out.println(mid2 - mid1);
        System.out.println(mid3 - mid2);
        System.out.println(end - mid3);
    }
}

Output is almost similar to :

2200211
835772
1255797
4651923

Answers


The speed difference between non-floating point (e.g. int math) addition/multiplication and bitwise operations is less than negligible on almost all machines.

There is no general way to turn an n-bit signed integer into its negative equivalent using only bitwise operations, as the negation operation looks like x = (~x) + 1, which requires one addition. However, assuming the signed integer is 32 bit you can probably write a bitwise equation to do this calculation. Note: do not do this.

The most common, readable way to negate a number is x = -x.


Java uses Complement Two representation. In order to change a sign, it means you must do a bitwise negation (it would be equivalent to xor with FFFF) and add 1.

x = ~x + 1;

I am almost sure that -x is, if anything, faster than that.


Solution using high level language

Questions like these are popular in interviews and competitive programming world .

I landed here researching more solution for negation of a number without using - or + operator .

For this :

  1. complement a number using ~ operator
  2. Then add 1 to the number obtained in step 1 using Half adder logic :

    int addNumbers(int x, int y) { 
                if(y==0) return x; // carry is 0 return 
                addNumbers(x^y,(x&y)<<1); }
    

Here x^y performs addition of bits and x&y handles carry operation


Need Your Help

Printing a statement only once in a while loop

java loops printing while-loop

This is probably very simple, however I have completely blanked and would appreciate some pointers. I'm creating a small game we have been assigned where we select numbers and are then provided a t...

SQL format of query

c++ sql qt5

I'm trying to use this query in a c++ (qt5 embedded):