What is fastest way to convert bool to byte?

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

    Hand-written IL:

    .method private hidebysig static 
        int32 BoolToInt (
            bool b
        ) cil managed noinlining 
    {
        .maxstack 8
    
        IL_0000: ldarg.0
        IL_0001: ldc.i4.0
        IL_0002: cgt.un
        IL_0004: ret
    }
    

    And they are jitted to few x86 codes:
    (clrjit.dll version 4.7.3131.0)

    test        cl,cl
    setne       al
    movzx       eax,al
    ret
    

    The only problem is that I have found no simple way to inline IL in C#. This answer is done using dnSpy.

提交回复
热议问题