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

后端 未结 3 595
终归单人心
终归单人心 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:41

    The method above does not work for me, using Swift 2 but I discovered a much more simpler method to do this conversion and vice versa:

    func binarytotype  (value: [UInt8], _: T.Type) -> T
    {
        return value.withUnsafeBufferPointer
        {
            return UnsafePointer($0.baseAddress).memory
        }
    }
    
    func typetobinary  (var value: T) -> [UInt8]
    {
        return withUnsafePointer(&value)
        {
            Array(UnsafeBufferPointer(start: UnsafePointer($0), count: sizeof(T)))
        }
    }
    
    let a: Double = 0.25
    let b: [UInt8] = typetobinary(a) // -> [0, 0, 0, 0, 0, 0, 208, 63]
    let c = binarytotype(b, Double.self) // -> 0.25
    

    I have tested it with Xcode 7.2 in the playground.

提交回复
热议问题