C语言的位运算的优势

2017-08-02

C语言的位运算的优势。位运算加速技巧：1 如果乘上一个2的倍数数值，可以改用左移运算(Left Shift) 加速 300%

1. 如果乘上一个2的倍数数值，可以改用左移运算(Left Shift) 加速 300%

x = x * 2;

x = x * 64;

//改为:

x = x << 1; // 2 = 21

x = x << 6; // 64 = 26

x = x / 2;

x = x / 64;

//改为:

x = x >> 1;// 2 = 21

x = x >> 6;// 64 = 26

x = int(1.232)

//改为:

x = 1.232 >> 0;

var t:int = a;

a = b;

b = t;

//equals:

a = a^b;

b = a^b;

a = a^b;

i = -i;

//改为

i = ~i + 1; // NOT 写法

//或

i = (i ^ -1) + 1; // XOR 写法

x = 131 % 4;

//equals:

x = 131 & (4 - 1);

isEven = (i % 2) == 0;

//equals:

isEven = (i & 1) == 0;

//写法1

i = x < 0 ? -x : x;

//写法2

i = (x ^ (x >> 31)) - (x >> 31);

//写法3

i=x^(~(x>>31)+1)+(x>>31);

eqSign = a * b > 0;

//equals:

eqSign = a ^ b > 0;

1. RGB 色彩分离

var 24bitColor:uint = 0xff00cc;

var r:uint = 24bitColor >> 16;

var g:uint = 24bitColor >> 8 & 0xFF;

var b:uint = 24bitColor & 0xFF;

RGB 色彩合并

var r:uint = 0xff;

var g:uint = 0x00;

var b:uint = 0xcc;

var 24bitColor:uint = r << 16 | g << 8 | b;

ps——尤其是在嵌入式中，位运算尤为重要!