【问题标题】:Swift 4 convert bytes to Int and ntohlSwift 4 将字节转换为 Int 和 ntohl
【发布时间】:2018-07-04 09:56:53
【问题描述】:

大家好,我一直在尝试将这个 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)))

但这不起作用,它崩溃说没有足够的位。非常感谢您的帮助,谢谢!

【问题讨论】:

    标签: objective-c swift byte


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 2020-03-01
      • 2011-02-19
      • 1970-01-01
      • 2011-04-16
      • 2016-03-04
      • 2016-02-20
      相关资源
      最近更新 更多