Converting a byte to a binary string in c#

后端 未结 4 1514
不思量自难忘°
不思量自难忘° 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:58

    If I understand correctly, you have 20 values that you want to convert, so it's just a simple change of what you wrote.

    To change single byte to 8 char string: Convert.ToString( x, 2 ).PadLeft( 8, '0' )

    To change full array:

    byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };
    string[] b = a.Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ).ToArray();
    // Returns array:
    // 00000010
    // 00010100
    // 11001000
    // 11111111
    // 01100100
    // 00001010
    // 00000001
    

    To change your byte array to single string, with bytes separated with space:

    byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };
    string s = string.Join( " ",
        a.Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ) );
    // Returns: 00000001 00001010 01100100 11111111 11001000 00010100 00000010
    

    if ordering of bytes is incorrect use IEnumerable.Reverse():

    byte[] a = new byte[] { 1, 10, 100, 255, 200, 20, 2 };
    string s = string.Join( " ",
        a.Reverse().Select( x => Convert.ToString( x, 2 ).PadLeft( 8, '0' ) ) );
    // Returns: 00000010 00010100 11001000 11111111 01100100 00001010 00000001
    

提交回复
热议问题