What is fastest way to convert bool to byte?

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

    // Warning! Brain-compiled code ahead!
    static readonly char[] HexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    public static string ToHex(this byte[] me)
    {
        if ( me == null ) return null;
        int ml = me.Length;
        char[] c = new char[2*ml];
    
        int cp = 0;
        for (int i = 0; i < ml; i++ )
        {
            c[cp++] = HexChars[me[i]&15];
            c[cp++] = HexChars[me[i]>>4];
        }
        return new string(c);
    }
    

提交回复
热议问题