我有一个带有字节列表的Data:[64,69,207,65,61,225,199,151]十六进制字符串等于:4045cf413de1c797我用这个函数获取字节:var bytes:[UInt64]= www.example.com {UInt64(bitPattern:data.map { UInt64(bitPattern: Int64($0)) } data is a Data type
当我把它转换成一个double时,我得到了错误的值,我尝试了几个函数来转换它:
实施例1:
extension Data {
enum Endianess {
case little
case big
}
func toFloat(endianess: Endianess = .little) -> Float? {
guard self.count <= 4 else { return nil }
switch endianess {
case .big:
let data = [UInt8](repeating: 0x00, count: 4-self.count) + self
return data.withUnsafeBytes { $0.load(as: Float.self) }
case .little:
let data = self + [UInt8](repeating: 0x00, count: 4-self.count)
return data.reversed().withUnsafeBytes { $0.load(as: Float.self) }
}
}
}
这个给我零
实施例2:
var f:Float = 0.0
memcpy(&f, bytes, 4)
结果:8.96831017167883e-44
实施例3:
let floatNb:Float = dataSliced.reversed().withUnsafeBytes { $0.load(as:
Float.self)
}
结果:0.11024397
如果没有reversed(),则会出现错误:致命错误:从未对齐的原始指针加载
实施例4:
extension Numeric {
init<D: DataProtocol>(_ data: D) {
var value: Self = .zero
let size = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} )
//assert(size == MemoryLayout.size(ofValue: value))
self = value
}
}
结果为:-4.089067083288947e-194
好的结果是:43.61917851948163
如何正确地将Data转换为Double?
任何帮助将不胜感激
1条答案
按热度按时间bxgwgixi1#
您的问题是使用
Float
而不是Double
作为目标。Float
仅使用前4个字节。