c# - 在c#中从二进制值转换为双精度时出错
问题描述
我正在尝试读取由c++程序制作的二进制文件。这个文件有一些数字,当我试图读取它们时,我得到了一个错误的值。double
double
这是从文件中读取的 HEX 值:
00-67-CC-02-B3-F7-40-CA
期望值:
0.2051076530529798
实际值:
-4.9596277989715114E+49
二进制文件类型:double
8字节(c++)
c#中的转换输出:( double
)binaryreader.ReadDouble()
这是代码:
reader = new BinaryReader(File.Open(path, FileMode.Open), Encoding.Default);
double value = reader.ReadDouble();
我已经检查过了,我在正确的位置使用了这个命令。为什么我有这个不同的价值?
解决方案
让我们看看expected
repesented as byte
s:
double expected = 0.2051076530529798;
string result = string.Join("-", BitConverter
.GetBytes(expected)
.Select(b => b.ToString("X2")));
Console.WriteLine(result);
结果:
66-CC-02-B3-F7-40-CA-3F
让我们将其与您的输入进行比较:
00-67-CC-02-B3-F7-40-CA // Your input
66-CC-02-B3-F7-40-CA-3F // Should be for 0.2051076530529798
看来您应该跳过 1
字节(您在错误的位置读取流)。
// I've assumed that the next byte is `3F`
// Your input without starting `00` but with final `3F`
string data = "67-CC-02-B3-F7-40-CA-3F";
double value = BitConverter.ToDouble(data
.Split('-')
.Select(item => Convert.ToByte(item, 16))
.ToArray(),
0);
Console.Write(value);
结果:
0.20510765305298
推荐阅读
- foreach - 为每个父母创建一个div?
- python - 如何在行创建期间向 QSqlRelationalTableModel 添加隐藏字段值?
- python - 连接到控制台的 PyCharm 卡住了
- flutter - Flutter:从 sharedPreferences-list 构建列表,具有即时可见的效果
- amazon-web-services - airflow.cfg 文件中的小写环境变量
- flutter - 使用时间戳的 Flutter 本地通知
- electron - 服务人员不在电子中工作,但在浏览器中工作得很好
- php - 如何格式化json的结构以满足另一种结构
- flutter - Flutter 升级后:参数类型 'Future
函数(文件)'不能分配给参数类型'FutureOr 函数(Uint8List)' - javascript - 从 Firebase Javascript 中检索特定数据