#### Archived

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

# Bitwise Operators in C++

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

## Recommended Posts

Hello! I''m just starting to learn C++ with "C++ for Dummies" and am getting to the parts about creating nested loops and functions. There was a brief section earlier in the book that focused on bitwise operators and base 16 math. Should I spend extra time studying bitwise operators before I continue? Do game programmers often use bitwise operators? Thank you for your time and thought.

##### Share on other sites
You use them often enough; like to mash multiple flags together you use the bitwise or operator | which are need frequently with DirectX.

If you need to mod 4 an integer you can just bitwise and it with 4.

If you twiddle bitmaps or sound streams you''ll need them there too.

Understanding hexadecimal is beneficial in all programming.

Magmai Kai Holmlor
- Not For Rent

##### Share on other sites

Definitely.

Bitwise ops are your friend. Very useful.

& : bitwise AND

Useful for checking if a bit is set in a bitflag.

Useful for making a counter "roll over" at powers of 2 (quicker than % operator) ex: i=(i+1)&255 is quicker than i=(i+1)%256

Useful for masking out 16/24/32 bit colors to extract the individual r/g/b values.

| : bitwise OR

Useful for setting individual bitflags.

Useful for putting together 16/24/32 bit color values.
ex: c = (r<<16)|(g<<8)|(b)

~ : bitwise NOT

I don''t use this one very much myself, but I''m sure it has plenty of uses.

##### Share on other sites
quote:
Original post by Anonymous Poster

~ : bitwise NOT

I don''t use this one very much myself, but I''m sure it has plenty of uses.

Bitwise NOT (~) is used for unsetting bits. For example, to set the least significant bit you''d use:

i |= 0x01

To ''unset'' that same bit:

i &= ~(0x01)

##### Share on other sites
Oh yeah, well my "Complete Idiot''s Guide to C++" is way
better than your "C++ for Dummies".
All in fun, really, sorry to be off-topic.
I''m not making fun, I really do own "The Complete Idiot''s
Guide to C++" by Paul Snaith. Thank God I do, I wrote a utility
in C but compiled it in C++ so I could get used to the
differences when the larger project would be compiled and
wouldn''t you know it, I named a variable ''new'' and couldn''t
figure out why it wouldn''t compile.

Create.

##### Share on other sites
Thanks for the heads-up, I''ll definitely give bitwise and hex another look. Funny thing about those new variables.

1. 1
2. 2
3. 3
4. 4
frob
11
5. 5

• 10
• 16
• 13
• 20
• 12
• ### Forum Statistics

• Total Topics
632173
• Total Posts
3004579

×