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
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
.)