[英]Swift 4 convert bytes to Int and ntohl
大家好,所以我一直在尝试将这一Objective-C代码转换为快速代码,但始终会遇到麻烦。 这是Objective-C代码:
int msgLength = *((int *) _inputBuffer.bytes);
msgLength = ntohl(msgLength);
这就是我设法得到的:
var msgLength = (inputBuffer.bytes).load(as: Int.self)
msgLength = Int(NSSwapBigLongToHost(UInt(msgLength)))
但这无法正常工作,并崩溃表示没有足够的位数。 非常感谢您的帮助!
C int
类型是32位整数(在当前所有Apple平台上),而Swift Int
在64位平台上是64位整数。
因此,在Swift中,您必须将UInt32
用于32位整数:
var msgLength = (inputBuffer.bytes).load(as: UInt32.self)
msgLength = UInt32(bigEndian: msgLength)
或者,如果您从NSData
切换到Data
:
let msgLength = UInt32(bigEndian:inputBuffer.withUnsafeBytes { $0.pointee })
(即使在C代码中, uint32_t
也比int
更适合于强调4个字节的读取。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.