C#:将字节数组转换为字符串并打印到控制台

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10940883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:50:55  来源:igfitidea点击:

C#: Converting byte array to string and printing out to console

c#

提问by MxLDevs

public void parse_table(BinaryReader inFile)
{
    byte[] idstring = inFile.ReadBytes(6);
    Console.WriteLine(Convert.ToString(idstring));
}

It is a simple snippet: read the first 6 bytes of the file and convert that to a string.

这是一个简单的片段:读取文件的前 6 个字节并将其转换为字符串。

However the console shows System.Byte[].

但是控制台显示System.Byte[].

Maybe I'm using the wrong class for conversion. What should I be using? It will eventually be parsing filenames encoded in UTF-8, and I'm planning to use the same method to read all filenames.

也许我使用了错误的类进行转换。我应该使用什么?它最终将解析以 UTF-8 编码的文件名,我计划使用相同的方法来读取所有文件名。

采纳答案by Tom Studee

It's actually:

其实是:

    Console.WriteLine(Encoding.Default.GetString(value));

or for UTF-8 specifically:

或专门针对 UTF-8:

    Console.WriteLine(Encoding.UTF8.GetString(value));

回答by Jesse Webb

I was in a predicament where I had a signedbyte array (sbyte[]) as input to a Test class and I wanted to replace it with a normal byte array (byte[]) for simplicity. I arrived here from a Google search but Tom's answer wasn't useful to me.

我陷入了困境,我有一个带符号的字节数组 ( sbyte[]) 作为 Test 类的输入,byte[]为了简单起见,我想用普通的字节数组 ( )替换它。我是通过谷歌搜索来到这里的,但汤姆的回答对我没有用。

I wrote a helper method to print out the initializer of a given byte[]:

我写了一个辅助方法来打印给定的初始化程序byte[]

public void PrintByteArray(byte[] bytes)
{
    var sb = new StringBuilder("new byte[] { ");
    foreach (var b in bytes)
    {
        sb.Append(b + ", ");
    }
    sb.Append("}");
    Console.WriteLine(sb.ToString());
}

You can use it like this:

你可以这样使用它:

var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }

The ouput is valid C# which can then just be copied into your code.

输出是有效的 C#,然后可以将其复制到您的代码中。

And just for completeness, here is the UnsignedBytesFromSignedBytesmethod:

为了完整起见,这里是UnsignedBytesFromSignedBytes方法:

// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
    var unsigned = new byte[signed.Length];
    Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
    return unsigned;
}

回答by Jammer

This is just an updated version of Jesse Webbs code that doesn't append the unnecessary trailing ,character.

这只是 Jesse Webbs 代码的更新版本,没有附加不必要的尾随,字符。

public static string PrintBytes(this byte[] byteArray)
{
    var sb = new StringBuilder("new byte[] { ");
    for(var i = 0; i < byteArray.Length;i++)
    {
        var b = byteArray[i];
        sb.Append(b);
        if (i < byteArray.Length -1)
        {
            sb.Append(", ");
        }
    }
    sb.Append(" }");
    return sb.ToString();
}

The output from this method would be:

此方法的输出将是:

new byte[] { 48, ... 135, 31, 178, 7, 157 }

回答by Daniel Ryan

I've used this simple code in my codebase:

我在我的代码库中使用了这个简单的代码:

static public string ToReadableByteArray(byte[] bytes)
{
    return string.Join(", ", bytes);
}

To use:

使用:

Console.WriteLine(ToReadableByteArray(bytes));

回答by Amir Twito

 byte[] bytes = { 1,2,3,4 };

 string stringByte= BitConverter.ToString(bytes);

 Console.WriteLine(stringByte);

回答by Derek

For some fun with linq and string interpolation:

对于 linq 和字符串插值的一些乐趣:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

测试用例:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

输出:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }