Get a mop and wipe it up!

Bitwise testing in C#

, posted: 29-Jun-2009 21:38

When an object has several properties that have only 2 possible states (eg ON/OFF, TRUE/FALSE, YES/NO, 1/0...), one option for storing this data is in the individual bits that make up an integer.

For example, the decimal number 6 can be expressed in binary as 110. This is made up of: 1x4 + 1x2 + 0x1 = 6.

Aside: I can see that this is useful when memory is extremely limited (eg embedded devices, portable devices), but personally I find this approach to be the antithesis of Clean Code, and try to avoid it. My preference is to have individual named boolean properties.

In order for me to remember how to test whether a particular bit is set, I'm posting this reminder:

[Test] public void Should_return_true_for_130_contains_128() { // this is asking, "for the decimal number 130, is the bit in the 128 position set"? Assert.IsTrue((130 & 128) == 128); } [Test] public void Should_return_false_for_130_contains_64() { // this is asking, "for the decimal number 130, is the bit in the 64 position set"? Assert.IsFalse((130 & 64) == 64); }


Other related posts:
How to get your Windows Azure hosted WordPress contact form working
NuPeek - a local NuGet and Symbol Server for .NET
Caliburn.Micro for Newbies Who Want to Write Clean WP7 Apps - Part 1: How to Configure a New Project With Folders

Add a comment

Please note: comments that are inappropriate or promotional in nature will be deleted. E-mail addresses are not displayed, but you must enter a valid e-mail address to confirm your comments.

Are you a registered Geekzone user? Login to have the fields below automatically filled in for you and to enable links in comments. If you have (or qualify to have) a Geekzone Blog then your comment will be automatically confirmed and placed in the moderation queue for the blog owner's approval.

Your name:

Your e-mail:

Your webpage:

dmw's profile

David White
New Zealand

Goon fan, .NET developer, contrarian seeker of truth