tags:

views:

1679

answers:

4
+10  Q: 

C# binary literals

Is there a way to write binary literals in C#, like prefixing hexadecimal with 0x? 0b doesn't work.

If not, what is an easy way to do it? Some kind of string conversion?

+11  A: 

Only integer and hex directly, I'm afraid (ECMA 334v4):

9.4.4.2 Integer literals Integer literals are used to write values of types int, uint, long, and ulong. Integer literals have two possible forms: decimal and hexadecimal.

To parse, you can use:

int i = Convert.ToInt32("01101101", 2);
Marc Gravell
A: 

While not possible using a Literal, maybe a BitConverter can also be a solution?

Michael Stum
BitConverter gets a bit tricky because it is machine-endian; and on your standard Intel, that means little-endian. Most people have difficulty reading little-endian literals...
Marc Gravell
Ouch, now i remember why I was always aware of but never used the BitConverter...
Michael Stum
+1  A: 

You can always create quasi-literals, constants which contain the value you are after:

const int b001 = 1;
const int b010 = 2;
const int b011 = 3;
// etc ...
Debug.Assert((b001 | b010) == b011);

If you use them often then you can wrap them in a static class for re-use.

However, slightliy off-topic, if you have any semantics associated with the bits (known at compile time) I would suggest using an Enum instead:

enum Flags
{ 
    First = 0,
    Second = 1,
    Third = 2,
    SecondAndThird = 3
}
// later ...
Debug.Assert((Flags.Second | Flags.Third) == Flags.SecondAndThird);
Markus Johnsson
+1  A: 

Though the string parsing solution is the most popular, I don't like it, because parsing string can be a great performance hit in some situations.

When there is needed a kind of a bitfield or binary mask, I'd rather write it like

long bitMask = 1011001;

And later

int bit5 = BitField.GetBit(bitMask, 5);

Or

bool flag5 = BitField.GetFlag(bitMask, 5);`

Where BitField class is

public static class BitField
{
    public static int GetBit(int bitField, int index)
    {
        return (bitField / (int)Math.Pow(10, index)) % 10;
    }

    public static bool GetFlag(int bitField, int index)
    {
        return GetBit(bitField, index) == 1;
    }
}
Dmitry Tashkinov