Code Optimization

Interesting things in software development and code optimization

Bits, bytes and masks


Today we are going to learn how to apply mask to any type of data. We will look into mask itself, and apply a mask to an image.

Lets look into the image below to get general idea of mask:

As you can see we took the star mask and an image and got imaged star in output. Cool? :)

Hmm, what is going on and how to do it? Everything is very simple if you have learned my post about bit manipulations.

So, to do it we need the following things:

- bit mask;

- an image;

- go through each byte and apply AND operation for each couple of bytes (actually Int32 in my case as it is much faster).

Here is how:

Int32[] rgba_source = new Int32[256 * 256];

Int32[] rgba_dest = new Int32[256 * 256];

for (int i = 0; i < rgba_source.Length; i++)


rgba_dest[i] = rgba_dest[i] & rgba_source[i];


Here is the result of masking two images:

That's it, you have got like textured object/figure :).

Now, just imagine where you can use such approach and with which kind of data, as well as other operations like XOR and OR.

In short - it can be used in hash, crypto, visualization algorithms and much more.

One easiest encryption algorithm is just apply XOR for each char of string, for example:

string origin = "hello world";

string encoded = string.Empty;

string decoded = string.Empty;

for (int i = 0; i < origin.Length; i++)


encoded += (char)(origin[i] ^ 0x003F);


And we will get "WZSSPHPMS[" in the encoded variable, that is equal to hello world but just encoded. To decrypt/decode it, just make the same XOR:

for (int i = 0; i < encoded.Length; i++)


decoded += (char)(encoded[i] ^ 0x003F);


And you got your "hello world" string back again in the decoded variable.

Think about it and a lot of things you can do with that ;)

Thank you and see you next time.