What is fastest way to convert bool to byte?

前端 未结 9 1669
悲哀的现实
悲哀的现实 2020-12-15 06:23

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

相关标签:
9条回答
  • 2020-12-15 06:53

    How about

    byte x = Convert.ToByte(true);
    
    0 讨论(0)
  • 2020-12-15 06:55
    Convert.ToByte(myBool) 
    

    will give you 0 if myBool is False or 1 if it is True.

    0 讨论(0)
  • 2020-12-15 06:56

    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.

    0 讨论(0)
提交回复
热议问题