嘿,伙计们,所以我一直在尝试将这个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)))

但这不起作用,它崩溃了,说没有足够的比特。我真的很感谢你的帮助谢谢!

最佳答案

Cint类型是一个32位整数(在所有当前的苹果平台上),
而SwiftInt在64位平台上是64位整数。
因此,在Swift中,必须对32位整数使用UInt32

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个字节。)

07-27 13:37