简体   繁体   English

如何将字符串转换为字节数组?

[英]How to Convert String to Byte Array?

I am getting an error reading: 我在阅读时出现错误:

Cannot implicitly convert type 'String' to 'Byte[]' 无法将类型'String'隐式转换为'Byte []'

I think 'byte[]' is byte array - if it isn't please correct me. 我认为'byte []'是字节数组-如果不是,请更正我。

I have tried another solution on this website but I did not understand. 我在此网站上尝试了另一种解决方案,但我不理解。 I'm making ac# 'RTM tool' and this is what put in : 我正在制作ac#“ RTM工具”,这是放在里面的内容:

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

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

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 n字节到字符串的转换

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 . 相信这个答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM