Converting string to byte[] creates zero character

后端 未结 5 2886
死守一世寂寞
死守一世寂寞 2021-02-20 16:09

In this convert function

public static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCh         


        
5条回答
  •  长发绾君心
    2021-02-20 16:40

    Try to specify Encoding explicitly. You can use next code to convert string to bytes with specified encoding

    byte[] bytes = System.Text.Encoding.ASCII.GetBytes("abc");
    

    if you print contents of bytes, you will get { 97, 98, 99 } which doesn't contain zeros, as in your example In your example default encoding using 16 bits per symbol. It can be observer by printing the results of

    System.Text.Encoding.Unicode.GetBytes("abc"); // { 97, 0, 98, 0, 99, 0 }
    

    Then while converting it back, you should select the appropriate encoding:

    string str = System.Text.Encoding.ASCII.GetString(bytes);
    Console.WriteLine (str);
    

    Prints "abc" as you might expected

提交回复
热议问题