How to Convert String to Byte Array?

回眸只為那壹抹淺笑 提交于 2020-01-22 03:40:07

问题


I am getting an error reading:

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

I think 'byte[]' is byte array - if it isn't please correct me.

I have tried another solution on this website but I did not understand. I'm making a c# 'RTM tool' and this is what put in :

byte[] bytes = (metroTextBox2.Text);   
Array.Resize<byte>(ref bytes, bytes.Length + 1);   
PS3.SetMemory(0x2708238, bytes);

回答1:


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);



回答2:


    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
    }



回答3:


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.



来源:https://stackoverflow.com/questions/30545162/how-to-convert-string-to-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!