What is fastest way to convert bool to byte?

前端 未结 9 1684
悲哀的现实
悲哀的现实 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: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.

提交回复
热议问题