【问题标题】:Convert ByteArray to String for use in TextBox c#将 ByteArray 转换为 String 以用于 TextBox c#
【发布时间】:2012-09-04 03:14:23
【问题描述】:

是的,我已经阅读了大约 5 个小时的解决方案,但它们都不起作用。 BitConverter 只是创建一个空白字符串。

基本上我正在做的是尝试创建一个关卡阅读器,它将通过十六进制读取关卡内容并最终将其显示在树视图中。所以我要做的第一件事是创建一个字节数组,我可以在其中编辑数据,我已经做到了。 但是,现在我想在屏幕上显示数据。据我所知,您不能在屏幕上显示字节数组,您必须先将其转换为字符串。

这就是我想要做的:

        using (OpenFileDialog fileDialog = new OpenFileDialog())
        {
            if (fileDialog.ShowDialog() != DialogResult.Cancel)
            {
                textBox1.Text = fileDialog.FileName;
                using (BinaryReader fileBytes = new BinaryReader(new MemoryStream(File.ReadAllBytes(textBox1.Text))))
                {
                    string s = null;
                    int length = (int)fileBytes.BaseStream.Length;
                    byte[] hex = fileBytes.ReadBytes(length);
                    File.WriteAllBytes(@"c:\temp_file.txt", hex);
                }
            }
        }
    }

注意:我已经删除了我的转换尝试,因为我没有尝试过任何工作。 有谁知道我如何使用这些数据并将其转换为字符串,并将其添加到文本框中? (当然,我知道如何做后者。我遇到困难的是前者。) 如果有,请举例说明。

我可能应该让自己更清楚;我不想将字节转换为相应的字符(即如果它是 0x43,我不想打印'C'。我想打印'43'。

【问题讨论】:

  • 我怀疑你不知道 - 但是你的二进制文件格式使用什么文本编码?
  • 问题是,我们不知道您尝试了哪些解决方案。 IE。你见过this answer吗?另外,将字节数组包装在二进制读取器的内存流中,然后再转换回字节数组有什么用?
  • @Damien_The_Unbeliever - 接受的答案中的两种方法都有效;但它们仅适用于大约 10kb 的文件。其他任何事情都需要很长时间才能实现。 (阅读时间超过 1 分钟)。有什么想法吗?

标签: c# arrays string type-conversion


【解决方案1】:

首先,您只需将字节转换为更有用的东西,例如 UTF8,然后您可以从中获取字符串。 类似的东西(在我的例子中:iso-8859-1):

buf = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, buf);
tempString = Encoding.UTF8.GetString(buf, 0, count);

【讨论】:

  • 如果源数据不是字符串,在此之后它不会变得更好......并且也可能会简单地抛出,因为并非每个字节序列都是有效的 UTF8 序列。
【解决方案2】:

你知道你的字节数组是以哪种编码存储的吗?

你需要Encoding.GetString方法

这里是MSDN 示例

using System;
using System.IO;
using System.Text;

public class Example
{
   const int MAX_BUFFER_SIZE = 2048;
   static Encoding enc8 = Encoding.UTF8;

   public static void Main()
   {
      FileStream fStream = new FileStream(@".\Utf8Example.txt", FileMode.Open);
      string contents = null;

      // If file size is small, read in a single operation. 
      if (fStream.Length <= MAX_BUFFER_SIZE) {
         Byte[] bytes = new Byte[fStream.Length];
         fStream.Read(bytes, 0, bytes.Length);
         contents = enc8.GetString(bytes);
      }
      // If file size exceeds buffer size, perform multiple reads. 
      else {
         contents = ReadFromBuffer(fStream);
      }
      fStream.Close();
      Console.WriteLine(contents);
   }

   private static string ReadFromBuffer(FileStream fStream)
   {
        Byte[] bytes = new Byte[MAX_BUFFER_SIZE];
        string output = String.Empty;
        Decoder decoder8 = enc8.GetDecoder();

        while (fStream.Position < fStream.Length) {
           int nBytes = fStream.Read(bytes, 0, bytes.Length);
           int nChars = decoder8.GetCharCount(bytes, 0, nBytes);
           char[] chars = new char[nChars];
           nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0);
           output += new String(chars, 0, nChars);                                                     
        }
        return output;
    }
}
// The example displays the following output: 
//     This is a UTF-8-encoded file that contains primarily Latin text, although it 
//     does list the first twelve letters of the Russian (Cyrillic) alphabet: 
//      
//     А б в г д е ё ж з и й к 
//      
//     The goal is to save this file, then open and decode it as a binary stream.

编辑

如果您想以十六进制格式打印出字节数组,BitConverter 就是您要查找的形式,这里是MSDN 示例

// Example of the BitConverter.ToString( byte[ ] ) method. 
using System;

class BytesToStringDemo
{
    // Display a byte array with a name. 
    public static void WriteByteArray( byte[ ] bytes, string name )
    {
        const string underLine = "--------------------------------";

        Console.WriteLine( name );
        Console.WriteLine( underLine.Substring( 0, 
            Math.Min( name.Length, underLine.Length ) ) );
        Console.WriteLine( BitConverter.ToString( bytes ) );
        Console.WriteLine( );
    }

    public static void Main( )
    {
        byte[ ] arrayOne = {
             0,   1,   2,   4,   8,  16,  32,  64, 128, 255 };

        byte[ ] arrayTwo = {
            32,   0,   0,  42,   0,  65,   0, 125,   0, 197,
             0, 168,   3,  41,   4, 172,  32 };

        byte[ ] arrayThree = {
            15,   0,   0, 128,  16,  39, 240, 216, 241, 255, 
           127 };

        byte[ ] arrayFour = {
            15,   0,   0,   0,   0,  16,   0, 255,   3,   0, 
             0, 202, 154,  59, 255, 255, 255, 255, 127 };

        Console.WriteLine( "This example of the " +
            "BitConverter.ToString( byte[ ] ) \n" +
            "method generates the following output.\n" );

        WriteByteArray( arrayOne, "arrayOne" );
        WriteByteArray( arrayTwo, "arrayTwo" );
        WriteByteArray( arrayThree, "arrayThree" );
        WriteByteArray( arrayFour, "arrayFour" );
    }
}

/*
This example of the BitConverter.ToString( byte[ ] )
method generates the following output.

arrayOne
--------
00-01-02-04-08-10-20-40-80-FF

arrayTwo
--------
20-00-00-2A-00-41-00-7D-00-C5-00-A8-03-29-04-AC-20

arrayThree
----------
0F-00-00-80-10-27-F0-D8-F1-FF-7F

arrayFour
---------
0F-00-00-00-00-10-00-FF-03-00-00-CA-9A-3B-FF-FF-FF-FF-7F
*/

【讨论】:

  • +1。如果源是文本很有用(问题似乎也不是这种情况)。
  • @AlexeiLevenkov,如果我们想将字节数组转换为文本,它应该包含任何编码的文本字节,我错了吗?
  • 我不知道 OP 想要什么“将字节数组转换为文本”......但听起来 OP 至少希望有可打印的输出(可能字符至少在 0-31 范围之外)。在大多数情况下,您的示例不会提供可打印的输出,不确定“任何编码”是什么意思:如果源是文本并且您选择了错误的编码 - 如果源是随机的,则将获得不可用的输出(或无效 UTF8 序列的例外)字节序列它不能用任何正常的编码转换为可打印的文本......
  • 啊,是的@AlexeiLevenkov,你是对的,如果我们的意思是可打印输出,我的代码就没用了
  • 我可能应该让自己更清楚;我不想将字节转换为相应的字符(即如果它是 0x43,我不想打印'C'。我想打印'43'。
【解决方案3】:

您可以将数据转换为十六进制:

  StringBuilder hex = new StringBuilder(theArray.Length * 2);
  foreach (byte b in theArray)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();

【讨论】:

  • +1。这将使您获得十六进制...通常使用更高级的 LINQ 单语句来完成 :) 但这对于非专家来说更具可读性。
  • 我尝试这样做,并且在打印时,它打印的所有内容都是System.Byte[]。这就是我所做的:pastebin.com/XTJW2iAS 阅读:length 在我的原始帖子中定义。我可能做错了什么......
  • 很简单... textBox2.Text = hex.ToString();应该是 textBox2.Text = hex1.ToString(); hex1 而不是 hex ...
  • 哦! >
  • 是的,这似乎需要很长时间才能实现。我刚刚尝试使用另一个文件,它花了 60 多秒。有什么想法,我是实施错了还是很慢?
【解决方案4】:

确实没有默认的方式来显示随机字节序列。选项:

  • base64 编码 (Convert.ToBase64String) - 将产生不可读但至少可安全打印的字符串
  • 十六进制编码每个字节并在每个字节的表示之间用空格连接,可能分成每行几个(即 16 个)字节的组。 - 将产生更多类似黑客的视图。
  • 将所有字节映射到可打印的字符(可能是彩色的)并可能分成多行 - 将产生类似矩阵的数据视图...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多