• Advertisement

Archived

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

Bit manipulation

This topic is 5527 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

Which are some good books specifically geared to bit manipulation in C? Thanks, Arshad

Share this post


Link to post
Share on other sites
Advertisement
That''s like asking for a book on the word ''The'' in the English language. Bit manipulation is quite trivial, really. What do you want to understand? I''m sure we can answer your question.

[ MSVC Fixes | STL | SDL | Game AI | Sockets | C++ Faq Lite | Boost | Asking Questions | Organising code files | My stuff ]

Share this post


Link to post
Share on other sites
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