Michael Michael - 1 year ago 129
Swift Question

How do I set integer endianness using htonl in Swift?

I'm trying to set integer endianness using

in Swift but the compiler isn't finding the

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'

Answer Source

Update: Martin R's answer is the correct answer for current versions of Swift: http://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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download