简体   繁体   English

Swift 4将字节转换为Int和Ntohl

[英]Swift 4 convert bytes to Int and ntohl

Hey guys so I've been trying to convert this objective-c code to swift but keep stumbling on problems with it. 大家好,所以我一直在尝试将这一Objective-C代码转换为快速代码,但始终会遇到麻烦。 Heres the objective-c code: 这是Objective-C代码:

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! 非常感谢您的帮助!

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. C int类型是32位整数(在当前所有Apple平台上),而Swift Int在64位平台上是64位整数。

Therefore in Swift you'll have to use UInt32 for 32-bit integers: 因此,在Swift中,您必须将UInt32用于32位整数:

var msgLength = (inputBuffer.bytes).load(as: UInt32.self)
msgLength = UInt32(bigEndian: msgLength)

Or, if you switch from NSData to Data : 或者,如果您从NSData切换到Data

let msgLength = UInt32(bigEndian:inputBuffer.withUnsafeBytes { $0.pointee })

(Even in the C code uint32_t would be better suited than int to emphasize that 4 bytes are read.) (即使在C代码中, uint32_t也比int更适合于强调4个字节的读取。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM