【问题标题】:How to Convert String to Byte Array?如何将字符串转换为字节数组?
【发布时间】:2015-08-13 05:45:34
【问题描述】:

我得到一个错误的阅读:

无法将类型“String”隐式转换为“Byte[]”

我认为 'byte[]' 是字节数组 - 如果不是,请纠正我。

我在这个网站上尝试了另一种解决方案,但我不明白。我正在制作一个 c# 'RTM 工具',这就是放入的内容:

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

【问题讨论】:

标签: c# bytearray


【解决方案1】:

试试这个,

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

归功于this answer

【讨论】:

  • 好吧,如果您发布此答案,我认为评论中的链接就足够了。如果你明白我的意思。
  • 我觉得现在没问题.. ;)
  • 没用,谢谢你的尝试,非常感谢:)
  • 是的,它被发布了多次,所以我可以再分享一个链接,但最好是发布答案而不是链接。
【解决方案2】:

你可以这样试试:

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

并解码:

var decodeString = System.Text.Encoding.UTF8.GetString(bytes);

【讨论】:

  • 不幸的是,这对我没有用,可能是因为我在我的一端塞满了 :) 抱歉,感谢您的帮助。
  • @JacobReid:- 不客气。我不确定您面临什么问题,因为这种方法在大多数情况下都有效!
  • 我现在没有收到错误,这很好,但它仍然没有做我想做的事,不是你的错,谢谢:)
【解决方案3】:
    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
    }

【讨论】:

    猜你喜欢
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多