Converting NSData to Integer in Swift

后端 未结 7 2084
予麋鹿
予麋鹿 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:19

    You can extend Data type, create a generic method, get the bytes and cast it or set the resulting type explicitly as needed:

    extension Data {
        func object(at index: Index = 0) -> T {
            subdata(in: index...size))
            .withUnsafeBytes { $0.load(as: T.self) }
        }
    }
    

    extension Numeric {
        var data: Data {
            var source = self
            return Data(bytes: &source, count: MemoryLayout.size)
        }
    }
    

    let data = Data([0xFF, 0x1F])   // 2 bytes
    
    let uint16: UInt16 = data.object()      // 8191  littleEndian
    let number1 = uint16.littleEndian       // 8191
    let number2 = uint16.bigEndian          // 65311
    
    let int16 = data.object() as Int16      // 8191   littleEndian
    let number3 = int16.littleEndian        // 8191
    let number4 = int16.bigEndian           // -225
    
    print(number1) // 8191
    print(number2) // 65311
    print(number3) // 8191
    print(number4) // -225
    

    Testing with Int

    let random = Int.random(in: 1...100)    // 15 UInt32
    let data = random.data                  // 8 bytes  [15, 0, 0, 0, 0, 0, 0, 0]
    

    Testing with UInt32

    let random = UInt32.random(in: 1...100)  // 90 UInt32
    let data = random.data                   // 4 bytes  [90, 0, 0, 0]
    

    Testing with Double

    let random = Double.random(in: 0...1)  // 0.2463145485351322 Double
    let data = random.data                 // 8 bytes  [12, 99, 62, 49, 60, 135, 207, 63]
    

    If you want to extract a subdata:

    let data = Data([0xFF, 0x1F, 0x1F, 0xFF])      // 4 bytes
    
    let uint16: UInt16 = data.object(at: 2)        //  65311 littleEndian
    let number1 = uint16.littleEndian              // 65311
    let number2 = uint16.bigEndian                 // 8191
    
    let int16: Int16 = data.object(at: 2)          // -225   littleEndian
    let number3 = int16.littleEndian               // -225
    let number4 = int16.bigEndian                  // 8191
    
    number1 // 65311
    number2 // 8191
    number3 // -225
    number4 // 8191
    

提交回复
热议问题