M. Salih Kocak
M. Salih Kocak

Reputation: 189

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.

Upvotes: 1

Views: 6792

Answers (2)

Keenle
Keenle

Reputation: 12190

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))

Upvotes: 8

M. Salih Kocak
M. Salih Kocak

Reputation: 189

I found a way to convert it but not directly. First i create an array with length 1(i know that it will be 1 element in array), then i copy the NSData value into that array then take the first element. It is like:

    var lengthData:NSData = buffer.subdataWithRange(NSMakeRange(12,4))
    var array = Int[](count: 1, repeatedValue: 1)
    lengthData.getBytes(&array, length:1)
    var length:Int = array[0]

This helped me but any direct conversions will be appreciated too.

Upvotes: 0

Related Questions