问题描述
伙计们,所以我一直在尝试将这个Objective-C代码转换为快速代码,但始终会遇到麻烦。以下是目标C代码:
Hey guys so I've been trying to convert this objective-c code to swift but keep stumbling on problems with it. Heres the objective-c code:
int msgLength = *((int *) _inputBuffer.bytes);
msgLength = ntohl(msgLength);
,这里是我设法得到的东西:
and heres what I managed to get:
var msgLength = (inputBuffer.bytes).load(as: Int.self)
msgLength = Int(NSSwapBigLongToHost(UInt(msgLength)))
但这不起作用,它崩溃表示没有足够的位数。非常感谢您的帮助!
but this isn't working, it crashes saying there isn't enough bits. I really appreciate the help thanks!
推荐答案
C int
类型为一个32位整数(在当前所有Apple平台上)为
,而Swift Int
在64位平台上为64位整数。
The C int
type is a 32-bit integer (on all current Apple platforms),whereas the Swift Int
is 64-bit integer on 64-bit platforms.
因此,在Swift中,您必须对32位整数使用 UInt32
:
Therefore in Swift you'll have to use UInt32
for 32-bit integers:
var msgLength = (inputBuffer.bytes).load(as: UInt32.self)
msgLength = UInt32(bigEndian: msgLength)
或者,如果您从 NSData
切换到 Data
:
Or, if you switch from NSData
to Data
:
let msgLength = UInt32(bigEndian:inputBuffer.withUnsafeBytes { $0.pointee })
(即使在C代码 uint32_t
中也更合适比 int
强调读取4个字节。)
(Even in the C code uint32_t
would be better suited than int
to emphasize that 4 bytes are read.)
这篇关于Swift 4将字节转换为Int和Ntohl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!