假设我有一些二进制数据被转换为32位整数而不是32位浮点(小端),我该如何纠正?
例如:1155186688
应为1750
float(00 C0 DA 44
hex)。
答案 0 :(得分:5)
Struct用于将类型打包和解包为字节。
将整数转换回字节,然后转换为float:
>>> my_bytes = struct.pack('I', 1155186688) # 'I' = Unsigned Int
b'\x00\xc0\xdaD'
>>> my_float = struct.unpack('f', my_bytes)[0] # 'f' = float
1750
或长篇:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestsJson
{
class Model
{
public DateTime Date { get; set; }
public int Clicks { get; set; }
public Model(DateTime date, int clicks)
{
Date = date;
Clicks = clicks;
}
}
class Program
{
static void Main(string[] args)
{
var data = new List<Model>()
{
new Model(new DateTime(2017, 01, 21), 14),
new Model(new DateTime(2017, 01, 22), 17),
new Model(new DateTime(2017, 01, 23), 50),
new Model(new DateTime(2017, 01, 24), 0),
new Model(new DateTime(2017, 01, 25), 2),
new Model(new DateTime(2017, 01, 26), 0)
};
foreach (var model in data)
{
var json = "{" + JsonConvert.SerializeObject(model.Date.ToShortDateString()) + ":" + model.Clicks + "}";
Console.WriteLine(json);
}
Console.Read();
}
}
}