Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

bitwise operators - useful? ever?

Status
Not open for further replies.

pixalone

Technical User
Aug 5, 2002
2
US
I am reading Beginning Visual C++ by Ivor Horton, and having already known basic C++ (up to structures and a little bit of classes), I figured I wouldn't learn alot in the beginning chapters, but in chapter two he just introduced something new to me: bitwise operators. I understand how each operator works, with the truth table and all, but I don't understand how this could actually be used. Anyone know if these things are ever useful, and if so for what? -Thanks
 
They're very useful. Imagine you have a function that sets yes/no options for something, and there are 32 different options you can set. Any number of them can be active at any one time. Now, you can either write a function that takes 32 parameters, and every time you need to set a single option, you must first get the state of every other option (so that you can pass in the same values for the 31 options you don't want to change)--31 function calls, call a function, and pass in 32 parameters.

Or, you could just write a function that takes one integer (which in VC++ is 32 bits), and uses the individual bits of that integer to represent options. Now, all you need to do to change one option is get the state of all the options with a single function call, set the bit corresponding that option to 1 or 0, and call the function that only takes one parameter to set all 32 options at once.

Which would you rather do?
 
also, if speed is ever a big concern, bitwise math is faster.

i wouldnt say its something to consider for most situations in basic math but if you have a large for loop and you need every ounce of time you can get...bitwise shifts are faster than multiplication.

and you can use them in conjuction with enums if you assign your enum items correctly.

you can also store your data in binary if size is ever an issue. so manipulation/comparisions can be done w/ masks at that point.

these may not be everyday situations but it is nice to have the option.

txjump
 
thanks for the prompt replies. :)

it looks like bitwise operators could be useful after all, they 'seem' neat...reducing size and increasing speed is great and all....but my book doesn't explain them well, i don't know hexadecimal so i can't follow most of it. i don't see myself having advanced programs with a plethora of options anytime soon, so i'm gonna save it for later i guess. i was just curious.

thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top