Converting string to byte[] creates zero character

后端 未结 5 2742
死守一世寂寞
死守一世寂寞 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:52

    Just to clear the confusion about your answer, char type in C# takes 2 bytes. So, string.toCharArray() returns an array in which each item takes 2 bytes of storage. While copying to byte array where each item takes 1 byte storage, there occurs a data loss. Hence the zeroes showing up in result.
    As suggested, Encoding.ASCII.GetBytes is a safer option to use.

提交回复
热议问题