簡體   English   中英

C#:Int 到 Hex 字節轉換以寫入 Hex 文件

[英]C# : Int to Hex Byte conversion to write into an Hex File

我在將 integer 轉換為十六進制格式的字節數組以寫入我的十六進制文件時遇到問題。 我已經閱讀並嘗試了幾種解決方案,這些解決方案在這里和許多其他網站上都有過。

我從文本框中讀取了 integer 並將其轉換為這樣的 int:

int value= int.Parse(textEditValue.EditValue.ToString());

此數字的示例輸入如下:

int value= 568

我需要像這樣寫入十六進制文件:

38 36 35 //reversed version of 568 because of endiannes

我嘗試過的是:

byte[] intBytes = BitConverter.GetBytes(value);
Array.Reverse(intBytes); // Because the hex-file is little-endian
byte[] resultBytes = intBytes;

當上面的代碼運行時,它會寫入 hex 文件,如:

38 02 00 00

我如何寫入文件:

    for(int i = 0x289C; i >= 0x289C - resultBytes.Length; i--)
   {
        binaryWriter.BaseStream.Position = i;
        binaryWriter.Write(resultBytes[count]);
        count++;
    }

我感謝任何幫助或建議。

您的代碼對於將 integer 轉換為十六進制是正確的。

568的十六進制表示是00 00 02 38 - 所以小端顛倒,你最終得到你得到的。

要獲得您想要的 output,您需要查看它,而不是 integer,而是 ASCII 字符串。 如果您需要確保文本輸入可以轉換為 integer,您可以執行以下操作:

if (int.TryParse(textEditValue.EditValue.ToString(), out int myInt)){
    byte[] intBytes = Encoding.ASCII.GetBytes(textEditValue.EditValue.ToString());
    Array.Reverse(intBytes); // Because the hex-file is little-endian
    byte[] resultBytes = intBytes;
}
else {
    //Not a valid integer
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM