大家好,我一直在尝试将此 objective-c 代码转换为 swift,但一直遇到问题。这是 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 个字节。)
关于objective-c - Swift 4 将字节转换为 Int 和 ntohl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48438001/