[英]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.