Converting a byte to a binary string in c#

后端 未结 4 1511
不思量自难忘°
不思量自难忘° 2020-12-02 22:17

In c# I am converting a byte to binary, the actual answer is 00111111 but the result being given is 111111. Now I really

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 22:56

    Try this one:

    public static String convert(byte b)
    {
        StringBuilder str = new StringBuilder(8);
                int[] bl  = new int[8];
    
        for (int i = 0; i < bl.Length; i++)
        {               
            bl[bl.Length - 1 - i] = ((b & (1 << i)) != 0) ? 1 : 0;
        }
    
        foreach ( int num in bl) str.Append(num);
    
        return str.ToString();
    }
    

提交回复
热议问题