使用按位运算符改变符号 [英] Change sign using bitwise operators

查看:297
本文介绍了使用按位运算符改变符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改INT使用位运算符的标志?显然,我们可以使用 X * = - 1 X / = - 1 。是否有这样做的任何最快的方法?

我做了如下小的考验。只是出于好奇...

 公共类ChangeSign {
    公共静态无效的主要(字串[] args){
        INT X = 198347;
        INT回路= 1000000;
        诠释Ÿ;
        长启动= System.nanoTime();
        的for(int i = 0; I< LOOP;我++){
            Y =(〜X)+ 1;
        }
        长MID1 = System.nanoTime();
        的for(int i = 0; I< LOOP;我++){
            Y = -x;
        }
        长MID2 = System.nanoTime();
        的for(int i = 0; I< LOOP;我++){
            Y = X * -1;
        }
        长MID3 = System.nanoTime();
        的for(int i = 0; I< LOOP;我++){
            Y = X / -1;
        }
        长端= System.nanoTime();
        的System.out.println(MID1 - 启动);
        的System.out.println(MID2 - MID1);
        的System.out.println(MID3 - MID2);
        的System.out.println(完 - MID3);
    }
}

输出几乎类似于:

  2200211
835772
1255797
4651923


解决方案

非浮点之间的速度差(例如INT数学)加法/乘法和位运算小于上可以忽略不计,几乎所有的机器。

有仅使用按位操作来打开一个n位符号整数到其负当量,作为反运算看起来像 X =(〜X)+ 1 ,这需要一个补充。然而,假设有符号整数为32位,你可能可以写一个方程式逐位做到这一点的计算。 注意:不这样做。

否定了一些最常见的,易读的方式是 X = -x

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

解决方案

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.

这篇关于使用按位运算符改变符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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