How to Convert String to Byte Array?

后端 未结 3 1104
失恋的感觉
失恋的感觉 2021-01-17 08:11

I am getting an error reading:

Cannot implicitly convert type \'String\' to \'Byte[]\'

I think \'byte[]\' is byte array - if it

相关标签:
3条回答
  • 2021-01-17 08:19

    You can try like this:

    string str= "some string";
    var bytes = System.Text.Encoding.UTF8.GetBytes(str);
    

    And to decode:

    var decodeString = System.Text.Encoding.UTF8.GetString(bytes);
    
    0 讨论(0)
  • 2021-01-17 08:23

    Try this,

    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
    

    n byte to string conversion

    static string GetString(byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }
    

    Credit to this answer.

    0 讨论(0)
  • 2021-01-17 08:30
        static void Main(string[] args)
        {
            string inputStr = Console.ReadLine();
            byte[] bytes = Encoding.Unicode.GetBytes(inputStr);
            string str = Encoding.Unicode.GetString(bytes);
            Console.WriteLine(inputStr == str); // true
        }
    
    0 讨论(0)
提交回复
热议问题