Converting string to byte[] creates zero character

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

    First let's look at what your code does wrong. char is 16-bit (2 byte) in .NET framework. Which means when you write sizeof(char), it returns 2. str.Length is 1, so actually your code will be byte[] bytes = new byte[2] is the same byte[2]. So when you use Buffer.BlockCopy() method, you actually copy 2 bytes from a source array to a destination array. Which means your GetBytes() method returns bytes[0] = 32 and bytes[1] = 0 if your string is " ".

    Try to use Encoding.ASCII.GetBytes() instead.

    When overridden in a derived class, encodes all the characters in the specified string into a sequence of bytes.

    const string input = "Soner Gonul";
    
    byte[] array = Encoding.ASCII.GetBytes(input);
    
    foreach ( byte element in array )
    {
         Console.WriteLine("{0} = {1}", element, (char)element);
    }
    

    Output:

    83 = S
    111 = o
    110 = n
    101 = e
    114 = r
    32 =
    71 = G
    111 = o
    110 = n
    117 = u
    108 = l
    

提交回复
热议问题