【问题标题】:C# : Int to Hex Byte conversion to write into an Hex FileC#:Int 到 Hex Byte 转换以写入 Hex 文件
【发布时间】:2022-01-05 11:09:46
【问题描述】:

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

我从文本框中读取整数并将其转换为这样的 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++;
    }

感谢任何帮助或建议。

【问题讨论】:

  • 需要将十六进制值的 ASCII 字符串表示形式写入文件似乎很奇怪。这是如何使用的——它是一种锻炼吗?
  • 对于有特定要求的项目。 @500 - 内部服务器错误

标签: c# integer hex byte


【解决方案1】:

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

568 的十六进制表示形式是 00 00 02 38 - 对于小端序如此颠倒,你最终会得到你所得到的。

要获得所需的输出,您需要查看它,而不是整数,而是 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
}

【讨论】:

    猜你喜欢
    • 2019-06-04
    • 2012-08-01
    • 1970-01-01
    • 2013-08-07
    • 2021-12-13
    • 2016-03-23
    • 2011-06-02
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多