簡體   English   中英

如何將字符串轉換為字節數組?

[英]How to Convert String to Byte Array?

我在閱讀時出現錯誤:

無法將類型'String'隱式轉換為'Byte []'

我認為'byte []'是字節數組-如果不是,請更正我。

我在此網站上嘗試了另一種解決方案,但我不理解。 我正在制作ac#“ RTM工具”,這是放在里面的內容:

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

您可以這樣嘗試:

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

並解碼:

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
    }

嘗試這個,

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字節到字符串的轉換

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

相信這個答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM