Convert an Objective-C method into Swift for NSInputStream (convert bytes into double)

后端 未结 3 591
终归单人心
终归单人心 2021-01-15 06:13

I have the following code in Objective-C:

- (double)readDouble
{
    double value = 0.0;

    if ([self read:(uint8_t *)&value maxLength:8] != 8)
    {
          


        
3条回答
  •  囚心锁ツ
    2021-01-15 06:51

    Here is the updated version for Swift 3 beta 6 which is different, thanx to Martin.

    func binarytotype  (_ value: [UInt8], _ : T.Type) -> T
    {
        return value.withUnsafeBufferPointer
        {
            UnsafeRawPointer($0.baseAddress!).load(as: T.self)
        }
    }
    
    func typetobinary  (_ value: T) -> [UInt8]
    {
        var v = value
        let size = MemoryLayout.size
        return withUnsafePointer(to: &v)
        {
            $0.withMemoryRebound(to: UInt8.self, capacity: size)
            {
                Array(UnsafeBufferPointer(start: $0, count: size))
            }
        }    
    }
    
    let dd: Double = 1.23456             // -> 1.23456
    let d = typetobinary(dd)             // -> [56, 50, 143, 252, 193, 192, 243, 63]
    let i = binarytotype(d, Double.self) // -> 1.23456
    

提交回复
热议问题