Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set integer endianness using htonl in Swift?

Tags:

I'm trying to set integer endianness using htonl() in Swift but the compiler isn't finding the htonl() method.

I've been using this as my reference: Append NSInteger to NSMutableData

Here's my code:

import Foundation import CFNetwork import CoreFoundation  var data = NSMutableData() var number : UInt32 = 12 var convertedNumber : UInt32 = htonl(number) data.appendBytes(&convertedNumber, length: 4) 

I've just been running this in a playground. The error is:

Use of unresolved identifier 'htonl' 
like image 764
Michael Avatar asked Jun 24 '14 19:06

Michael


2 Answers

As of Xcode 6, Beta 3, all integer types have a bigEndian method which returns the big-endian representation of the integer and changes the byte order if necessary. Example:

var data = NSMutableData() var number : UInt32 = 0x12345678 var convertedNumber = number.bigEndian data.appendBytes(&convertedNumber, length: 4) print(data) // Output: <12345678> 

Update for Swift 3:

let data = NSMutableData() let number: UInt32 = 0x12345678 var convertedNumber = number.bigEndian data.append(&convertedNumber, length: 4) 

Or, using the new Data value type:

var data = Data() let number: UInt32 = 0x12345678 var convertedNumber = number.bigEndian withUnsafePointer(to: &convertedNumber) {     data.append(UnsafeRawPointer($0).assumingMemoryBound(to: UInt8.self), count: 4) } 
like image 153
Martin R Avatar answered Oct 31 '22 15:10

Martin R


Update: Martin R's answer is the correct answer for current versions of Swift: https://stackoverflow.com/a/24653879/195691

--

You should use the CFSwapInt32HostToBig() CoreFoundation method, as htonl is likely implemented as a C macro that will not work in swift.

However, it looks like this doesn't currently work in the Swift playground. I'm getting the error Playground execution failed: error: error: Couldn't lookup symbols: __OSSwapInt32 despite the fact that the CoreFoundation documentation now includes method signatures in Swift for its byte swapping methods.

Interestingly, it looks like at least part of <arpa/inet.h> has been ported to swift, as methods like inet_ntoa() and inet_addr() are available to Swift, but the htonl family is not.

like image 37
Alex Pretzlav Avatar answered Oct 31 '22 13:10

Alex Pretzlav