Converting NSData to Integer in Swift

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

    You might find this method useful if you are doing it a lot:

    func readInteger(data : NSData, start : Int) -> T {
        var d : T = 0
        data.getBytes(&d, range: NSRange(location: start, length: sizeof(T)))
        return d
    }
    

    The function takes as a parameter the start position in the data to read the numeric type and it returns a value of the a type inferred from whatever you are assigning it to.

    For example:

    let i : UInt32 = readInteger(data, 10);
    

    reads an 4 byte integer from position 10 in the data.

    If you change UInt32 to UInt16 it will read two bytes.

提交回复
热议问题