Saving Enums as Bytes - C#

I saw an idea presented today that caught my attention because it can tremendously save on the amount of memory needed to run an application. In general, most developers do not worry about the amount of memory being used because "memory is cheap". Some of us do not have that luxury though, specifically those who are working with IoT devices that are extremely limited in their memory offerings. I'm sure my toaster does not have more than a few Kilobytes of RAM available to it.

What I saw was a concept that will allow you to save up to 9 pieces of information using a single byte. As a refresher, a byte is comprised of 8 bits, each can be a 1 or a 0 respectively. For example, we know that the binary string 1111 1111 = 255 in base 10. I will not go deeper into this concept as it is outside the cope of this article.

So you might be thinking, how can we save 9 bits of information in a byte if it only contains 8 bits. Let's take a look at this example to explain.

For this to work we need to have an enum created so let's start with that.

enum Colors {
White = 0,
Blue = 1,
Red = 2,
Green = 4,
Purple = 8,
Pink = 16,
Aqua = 32,
Black = 64,
Orange = 128

The thing to notice is that I have assigned each color a bit representation inside of a byte. for example 0000 0000 = 0 = White; 1000 0000 = 128 = Orange. You should now see where I am going. As long as the bits do not overlap you will always be able to reverse engineer this.

If we then ask the user what their favorite color is most of us would save this in an object that has a parameter called FavColor and then set it equal to the Colors.Blue or whatever their favorite color would be. That would take far more memory, I don't know exactly how much more as I didn't profile this, but I guarantee it is more than a single byte.

We could also turn this into a list of favorite colors as well. Say I like Blue and Green so I choose both. This would set my byte to a value of 0000 0101 meaning I like Blue and Green. There are some clever uses of & and | and ^ on this as well to help parse up the byte, but I am going to leave that to your imagination for now as I have other articles that will explore this concept in more detail.

22 views0 comments

Recent Posts

See All