简体   繁体   English

C#:Int 到 Hex 字节转换以写入 Hex 文件

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

I'm having problems in converting an integer into a byte array in hex format to write into my Hex File.我在将 integer 转换为十六进制格式的字节数组以写入我的十六进制文件时遇到问题。 I have read and tried several solutions that I went over in here and in many other sites.我已经阅读并尝试了几种解决方案,这些解决方案在这里和许多其他网站上都有过。

I read the integer from the textbox and convert it into an int like that:我从文本框中读取了 integer 并将其转换为这样的 int:

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

An example input of this number is like:此数字的示例输入如下:

int value= 568

And I need to write into the hex file like that:我需要像这样写入十六进制文件:

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

What I have tried is:我尝试过的是:

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

When the above code runs it writes into the hex file like:当上面的代码运行时,它会写入 hex 文件,如:

38 02 00 00

How I wrote into the file:我如何写入文件:

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

I appreciate any help or suggestion.我感谢任何帮助或建议。

Your code is correct for converting an integer to hex.您的代码对于将 integer 转换为十六进制是正确的。

The hex representation of 568 is 00 00 02 38 - so reversed for little Endian, you end up with what you got. 568的十六进制表示是00 00 02 38 - 所以小端颠倒,你最终得到你得到的。

To get your desired output you need to view it, not as integer, but as an ASCII string.要获得您想要的 output,您需要查看它,而不是 integer,而是 ASCII 字符串。 If you need to make sure the text input can be converted to an integer, you can do something like this:如果您需要确保文本输入可以转换为 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