简体   繁体   中英

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. 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!

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.

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)

Or, if you switch from NSData to 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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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