Bitwise Operators in C++

Started by
4 comments, last by Marigold 22 years, 8 months ago
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.
Advertisement
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
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

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.






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)
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.
Thanks for the heads-up, I''ll definitely give bitwise and hex another look. Funny thing about those new variables.

This topic is closed to new replies.

Advertisement