String to Bitmask

12 09 2014

Going to be a short post and unlike other times when I’ve said it and then went on to having a series of four posts, this time I mean it.

So, first, what brought this on?

Well, having tired somewhat of Unity‘s implementation I’ve decided to play around and write my own Entity.Component.System framework. For a game (of which I shall write about at a later date when there’s something playable).

In the process of writing it I’ve come to the conclusion that I need to twiddle some bits and because I’m quite pedantic it means I need to write tests for this.

Given my unit testing framework (NUnit) I’ve run into some issues when using the “TestCase” attribute. This (and other considerations) resulted in me digging through some old utilities and presto! Converting a string representation to a bitmask. A quick cleanup (it was written in C) and, presto! Let me introduce you all to the new utility on the block.

public static class GenerateBitmaskFromString
{
 public static Bitmask Perform(string line)
 {
  var mask = 0L;
  for (var i = line.Length - 1; i >= 0; --i)
  {
   if (line[i] == '1')
    mask |= 1L << ((line.Length - 1) - i);
  }
  return new Bitmask(mask);
 }
}

The Bitmask object itself is a simple struct wrapper around an Int64 or Int32 (depending on the platform) which provides some extra twiddling (is that… is that a word?) functionality.

I’m assuming knowledge of bit shifting and binary logic by people reading this. And also note that the order of character processing is reversed since given strings are usually in the form of “0000001” with their first character being the left most (ie. length-1) while bits are shifted rightwise.

Well, that’s it. Not very epic or grand but useful nonetheless.

He said, “We haven’t had that spirit here since nineteen sixty nine”

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: