如何在Swift中使用htonl设置整数字节序? [英] How do I set integer endianness using htonl in Swift?
问题描述
我正在尝试在Swift中使用 htonl()
设置整数字节序,但编译器找不到 htonl()
方法。
I'm trying to set integer endianness using htonl()
in Swift but the compiler isn't finding the htonl()
method.
我一直用这个作为参考:将NSInteger附加到NSMutableData
I've been using this as my reference: Append NSInteger to NSMutableData
这是我的代码:
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'
推荐答案
更新:对于当前版本的Swift,Martin R的答案是正确答案:https://stackoverflow.com/a/24653879/195691
Update: Martin R's answer is the correct answer for current versions of Swift: https://stackoverflow.com/a/24653879/195691
-
你应该使用 CFSwapInt32HostToBig()
CoreFoundation方法,因为 htonl
可能是作为C宏实现的,不能在swift中运行。
You should use the CFSwapInt32HostToBig()
CoreFoundation method, as htonl
is likely implemented as a C macro that will not work in swift.
然而,看起来这在Swift游乐场中当前不起作用。我收到错误 Playground执行失败:错误:错误:无法查找符号:__OSSwapInt32
尽管CoreFoundation文档现在包含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.
有趣的是,它看起来至少是< arpa / inet.h>
的一部分了移植到swift,因为像 inet_ntoa()
和 inet_addr()
这样的方法可用于Swift,但 htonl
家庭不是。
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.
这篇关于如何在Swift中使用htonl设置整数字节序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!