簡體   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