0

Take this enum:

[Flags]
public enum Colors
{
  NONE = 0,
  RED = 1,
  BLUE = 2,
  YELLOW = 4,
  BLACK = 8,
  WHITE = 16
}

I want to save a selection of those colors as a human readable string that represents a byte. For example,

Colors choice = Colors.RED | Colors.WHITE

should come out as

"00010001"

What would be the best way to achieve this?

Lixyna
  • 15
  • 6

1 Answers1

3

Let's make the representation step by step:

  1. We want integer, not enum: (int) choice
  2. Be in binary format Convert.ToString((int) choice, 2)
  3. Finally, we want at least 8 digits; so we have to pad by '0' if necessary: .PadLeft(8, '0')

Combining all together:

 string result = Convert.ToString((int) choice, 2).PadLeft(8, '0');
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Adding a link to the used [Convert.ToString](https://learn.microsoft.com/en-us/dotnet/api/system.convert.tostring?view=netcore-3.1#System_Convert_ToString_System_Int32_System_Int32_) overload and also the [wikipedia](https://en.wikipedia.org/wiki/Radix) article about radix/ base – MindSwipe Aug 05 '20 at 09:27