Skip to main content
gamedev.net
🔒 Locked

Bit manipulation

Started by asyed 2 replies 650+ views
Original Post
asyed
asyed
Which are some good books specifically geared to bit manipulation in C? Thanks, Arshad
Nypyren
Nypyren
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]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.