Sponsored By

String to Bitmask

In which I detail a simple but useful utility to convert string representations of a bitmask into a bitmask value.

Amir Barak, Blogger

September 10, 2014

2 Min Read

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 ch_index = line.Length - 1; ch_index >= 0; --ch_index)
            {
                if (line[ch_index] == '1')
                    mask |= 1L << ((line.Length - 1) - ch_index);
            }

            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"

Read more about:

2014Blogs

About the Author(s)

Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like