C#:Int到十六进制字节的转换,以写入到十六进制文件中



我在将整数转换为十六进制格式的字节数组以写入我的十六进制文件时遇到问题。我在这里和许多其他网站上阅读并尝试了几种解决方案。

我从文本框中读取整数,并将其转换为如下的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;

当上面的代码运行时,它会写入十六进制文件,如:

38 02 00 00

我如何写入文件:

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

我感谢任何帮助或建议。

您的代码将整数转换为十六进制是正确的。

568的十六进制表示是00 00 02 38——所以对于小Endian来说,相反,你最终得到了你所得到的。

要获得所需的输出,您需要查看它,而不是整数,而是ASCII字符串。如果你需要确保文本输入可以转换成整数,你可以这样做:

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
}

最新更新