What is fastest way to convert bool to byte?
I want this mapping: False=0, True=1
Note: I don\'t want to use any if
statements or other conditio
How about
byte x = Convert.ToByte(true);
Convert.ToByte(myBool)
will give you 0 if myBool is False or 1 if it is True.
You can use this struct to do similar to ChaosPandion's solution, but with safe code.
[StructLayout(LayoutKind.Explicit)]
struct BoolByte
{
[FieldOffset(0)]
public bool flag;
[FieldOffset(0)]
public byte num;
}
...
bool someBool = true;
byte num = new BoolByte() { flag = someBool }.num;
I haven't benchmarked it, so I'm not sure how the speed compares.
[EDIT] Well I ran the benchmark with .NET 3.5 equivalent mono and it looks like this is ~10% slower than a plain if check (on my macbook pro). So forget about this one. I doubt .NET 4+ would make a difference there.