繁体   English   中英

如何将十六进制写入二进制文件 c# 的文本部分

[英]How to write hex into the text section of a binary file c#

如果我有一个十六进制字符串,例如“6C5A3003AF4668B42922879D02364878”

如何将其放入二进制文件的 ascii 部分。 我可以像这样手动完成:

这个

但是我还没有找到用代码解决这个问题的方法,它总是这样写在十六进制部分:

这个

我尝试过二进制编写器和文件流,但他们将其写入十六进制部分

任何帮助,将不胜感激

我实际上将它存储在一个名为 Data 的字节数组中,我已经这样做了:

for (int i = 0; i <Data.Length; i++)
{
    int offset = 32 - i;

    stream.Position = allData.Length - stuff; //last 32 bytes of the file
    stream.WriteByte(Data[i]); //writes it into the hex section not text section
}

比如我把十六进制代码GatewayServer(47-61-74-65-77-61-79-53-65-72-76-65-72)给程序看看程序是怎么工作的

byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data);
//write s = GatewayServer
Console.WriteLine(s);

将十六进制数据转换为字节数据:

  public static byte[] FromHex(string hex)
{
   hex = hex.Replace("-", "");
   byte[] raw = new byte[hex.Length / 2];
   for (int i = 0; i < raw.Length; i++)
   {
       raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
   }
   return raw;
}

并将字节写入现有文件

 public static void AppendAllBytes(string path, byte[] bytes)
{
    //argument-checking here.
    using (var stream = new FileStream(path, FileMode.Append))
    {
       stream.Write(bytes, 0, bytes.Length);
    }
}

并将字节写入新文件

public static void CreateFileAndWriteAllBytes(string path, byte[] bytes)
{
    //argument-checking here.
    using (var stream = new FileStream(path, FileMode.Create))
    {
       stream.Write(bytes, 0, bytes.Length);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM