Bit arithmetic in C language

Source: Internet
Author: User

Bit arithmetic acceleration technique
1. If you multiply the value of the previous 2, you can use the left shift operation to accelerate the 300%

x = x * 2;
x = x * 64;
Switch
x = x << 1; 2 = 21
x = x << 6; 64 = 26

2. If the number of multiples in addition to the previous 2, you can use the right-shift operation to accelerate 350%

x = X/2;
x = X/64;
Switch

x = x >> 1;//2 = 21
x = x >> 6;//64 = 26

3. numeric to integer acceleration 10%

x = Int (1.232)
Switch

x = 1.232 >> 0;

4. swap two values (swap) and use XOR to accelerate 20%

var t:int = A;
A = b;
b = t;
Switch
A = A^b;
b = a^b;
A = A^b;

5. sign conversion, can join 300%

i =-I.;
Switch
i = ~i + 1; Not notation
Or
i = (i ^-1) + 1; XOR notation


6. Take the remainder, if the divisor is a multiple of 2, can use the and operation to accelerate the 600%

x = 131% 4;
Switch
x = 131 & (4-1);

7. Use the and operation to check if the integer is a multiple of 2 to accelerate the 600%

IsEven = (i% 2) = = 0;
Switch
IsEven = (I & 1) = = 0;

8. Accelerate the writing of Math.Abs 600% 1, 2 is faster than the wording of 1 20%

Notation 1
i = x < 0? -x:x;

Notation 2

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

Notation 3

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

9. Compare if you have the same symbol after multiplying the two values, accelerating 35%

Eqsign = A * b > 0;
equals
Eqsign = a ^ b > 0;

Other bit arithmetic techniques:
1. RGB Color Separation

var 24bitcolor:uint = 0xff00cc;
var r:uint = 24bitColor >> 16;
var g:uint = 24bitColor >> 8 & 0xFF;
var b:uint = 24bitColor & 0xFF;

2. RGB Color Merge

var r:uint = 0xFF;
var g:uint = 0x00;
var b:uint = 0xcc;
var 24bitcolor:uint = r << 16 | G << 8 | b

Bit arithmetic in C language

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.