Search code examples
integerswiftnsdata

NSData to Swift Integer


I have an NSMutableData, i make subdata with its method for getting the exact bytes of the integer that i will create. But somehow i can not convert that bytes into integer. It seems okay when i am debugging i see the subdata value as "<04 00 00 00>" -which i need to convert-.

    var lengthData:NSData = buffer.subdataWithRange(NSMakeRange(12,4))
    var length:Int = //Conversion which must be done from lengthData
    var dataPart:NSData = buffer.subdataWithRange(NSMakeRange(16, length))

I tried to convert the lengthData to NSString and get the integer value of it but no-success. Can you please help about this conversion. Thanks in advance.


Solution

  • You can read required amount of bytes into the primitive type variable just by passing it's pointer to the .getBytes(...) function:

    var length: Int = 0
    data.getBytes(&length, range: NSRange(location: 12, length: 4))