• Advertisement

Archived

This topic is now archived and is closed to further replies.

Bit manipulation

This topic is 5621 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
I assume you're familiar with hex notation (0x100 = 256 decimal).

Bitwise Operators (a and b are 16-bit integers, c is the result):

c = ~a: reverses every bit in the integer.
Each bit:
a -> c
1 -> 0
0 -> 1
Example:
a = 0x1000
c = 0x7FFF
Common uses: In conjunction with other bitwise operators
(same as XOR with b having all bits 1)

c = a^b : XOR operation. "0 for same, 1 for different"
Each bit:
a,b -> c
0,0 -> 0
0,1 -> 1
1,0 -> 1
1,1 -> 0
Example:
a = 0x1005
b = 0xFFF0
c = 0xEFF5
Common uses: Switching certain bits to the opposite state.

c = a|b : OR operation. "if either is 1, result is 1"
a,b -> c
0,0 -> 0
0,1 -> 1
1,0 -> 1
1,1 -> 1
Example:
a = 0x1111
b = 0x0202
c = 0x1313
Common uses: Turning certain bits in a number ON

c = a&b : AND operation "if both are 1, result is 1"
a,b -> c
0,0 -> 0
0,1 -> 0
1,0 -> 0
1,1 -> 1
Example:
a = 0x1112
b = 0x0103
c = 0x0102
Common uses: Turning certain bits in a number OFF


!, && and || (the logical operators) can be thought of as converting non-zero integers into 1, and then using the bitwise operators (this is how you must overload them in C#, BTW).

[edited by - Nypyren on December 2, 2002 3:59:47 AM]

Share this post


Link to post
Share on other sites

  • Advertisement