Binary operations are handy little tools for computer scientists.
A lot of developers who have picked up programming along the way, and not received a rigorous education in the fundamentals of computer science might not see the value in such low-level structures. But, they are very useful under certain circumstances. Bit-arrays (which can be represented just as integers) can pack a tremendous amount of information into a tiny amount of space. And this really counts for a lot when you’re talking about an application that needs to scale.
It’s not just size that’s on your side with bit-arrays, but also speed. Bitwise operations are the fastest logical operations a computer can perform. So if you need to execute something over and over, if you can do it with bitwise operators you’ll see some screaming performance.
Each of the examples below will test the nth bit (from right to left) in the integer x.
Set a Bit
Use OR.
x | (1 << n)
Test a Bit
Use AND.
x & (1 << n)
Clear a Bit
Use XOR.
x ^ (1 << n)
Toggle a Bit
Use NOT.
x & ~(1 << n)
I've got a masters degree in computer science and over 10 years of experience building web-based systems using Java/J2EE, Ruby, Rails and PHP. I'm a strong believer in the effectiveness of Agile Methods.
2 Comments
Do these actually work in some language?
Not that I know of. You should be able to translate the concept into the language of your choice though. The operators I used are pretty standard.