字节数组的字符串表示

时间:2011-03-03 01:21:53

标签: c# string byte bytearray

我有一个表示字节的字符串

string s = "\x00af";

我把这个字符串写入一个文件,所以该文件包含文字“\ x00af”而不是它所代表的字节,后来我从文件中读取了这个字符串,我现在怎样才能将这个字符串再次视为字节(而不是文字)?

以下是示例代码:

public static void StringAndBytes()
{
    string s = "\x00af";
    byte[] b = Encoding.ASCII.GetBytes(s);

    // Length would be 1
    Console.WriteLine(b.Length);

    // Write this to a file as literal
    StreamWriter sw = new StreamWriter("c:\\temp\\MyTry.txt");
    sw.WriteLine("\\x00af");
    sw.Close();

    // Read it from the file
    StreamReader sr = new StreamReader("c:\\temp\\MyTry.txt");
    s = sr.ReadLine();
    sr.Close();

    // Get the bytes and Length would be 6, as it treat the string as string
    // and not the byte it represents
    b = Encoding.ASCII.GetBytes(s);
    Console.WriteLine(b.Length);
}

关于如何将字符串从文本转换为表示字节的字符串的任何想法? THX!

4 个答案:

答案 0 :(得分:1)

不确定我是否正确理解了该问题,但您没有将字符串s写入该文件。您的\声明中还有一个额外的WriteLineWriteLine("\\x00af")写了字符\x00af,因为第一个{{1}充当第二个逃脱......

你的意思是

\

sw.WriteLine("\x00af");

代替?这在我的测试中按预期工作。

答案 1 :(得分:1)

是否要求文件内容具有字符串文字?如果不是,那么您可能希望将byte[] b数组直接写入该文件。这样,当你阅读它时,它就是你所写的。

byte[] b = Encoding.UTF32.GetBytes(s);
File.WriteAllBytes ("c:\\temp\\MyTry.txt", b);

b = File.ReadAllBytes ("c:\\temp\\MyTry.txt");
s = Encoding.UTF32.GetString (b);

如果您需要文件内容具有字符串文字,并且能够将其转换为写入的原始文本,则必须选择正确的编码。我相信UTF32是最好的。

    b = new byte[4];
    b[0] = Byte.Parse(s.Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier);
    string v = Encoding.UTF32.GetString(b);
    string w = "\x00af";

    if (v != w)
        MessageBox.Show("Diff [" + w + "] = [" + v + "] ");
    else
        MessageBox.Show("Same");

答案 2 :(得分:0)

使用Encoding.ASCII.GetString(byte[])方法。它也可以从所有其他编码中获得。确保始终使用相同的编码来解码字节[],就像您对其进行编码一样,或者每次都不会得到相同的值。

Here就是一个例子。

答案 3 :(得分:0)

只需解析代表每个字节的字符串:

Byte b = Byte.Parse(s);