Converting NSData to Integer in Swift

后端 未结 7 2086
予麋鹿
予麋鹿 2021-01-05 02:29

In Objective-C the code looked liked this and worked flawlessly,

NSInteger random = arc4random_uniform(99) + 1 
NSData *data = [NSData dataWithBytes:& ra         


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 03:05

    For Swift 3, you can do this (little endian, but similar for big):

    func getInt(fromData data: Data, start: Int) -> Int32 {
      let intBits = data.withUnsafeBytes({(bytePointer: UnsafePointer) -> Int32 in
        bytePointer.advanced(by: start).withMemoryRebound(to: Int32.self, capacity: 4) { pointer in
          return pointer.pointee
        }
      })
      return Int32(littleEndian: intBits)
    }
    

    You can modify this, add generics, etc. to fit other primitive types (and vary it depending on the endianness of the data bytes).

提交回复
热议问题