What is fastest way to convert bool to byte?

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

    Since .NET Core 2.1 you can reinterpret the bool as a byte this way. This is branch-free and should be very fast, as it hardly needs to "do" anything.

    Technically, the true value could be any non-zero byte, but in practice, it is 1. That deserves some consideration. If you want absolute certainty, you could look for an efficient, branch-free way to turn a byte into 1 if it is non-zero, or leave it 0 otherwise. (Two approaches come to mind: A) Smear the bits so that either all bits are 0 or all bits are 1, then do & 1 to get either 0 or 1. B) Take 0 - n as an int, which will be either zero or negative. Shift the sign bit so that it becomes the least significant bit, resulting in either 0 or 1.)

提交回复
热议问题