ios - 如何将 UInt32 转换为 UInt8

标签 ios swift

我需要快速将 UInt32 附加到 NSMutableData 对象。问题是,我不知道如何访问 int 中的特定字节。

这是我尝试过的:

extension NSMutableData {

  enum Endianness {
    case LittleEndian, BigEndian
  }

  func appendUInt32(myInt: UInt32, endianness: Endianness = .LittleEndian) {
    var bytes = UInt8[]()
    for i in 0..sizeof(UInt32) {
      switch endianness {
        case .LittleEndian:
          bytes.append(UInt8(myInt >> i))
        case .BigEndian:
          bytes.append(UInt8(myInt >> (sizeof(UInt32) - 1 - i)))
      }
    }
    self.appendBytes(bytes, length:bytes.count)
  }
}

这会引发编译器异常,我无法将其从 UInt32 转换为 UInt8。有没有一种简单的方法可以简单地访问 UInt32 中的字节?

编辑: 从评论中总结最终解决方案:

extension NSMutableData {

  enum Endianness {
    case LittleEndian, BigEndian
  }

  func appendUInt32(myInt: UInt32, endianness: Endianness = .LittleEndian) {
    var bytes = UInt8[]()
    for i in 0..sizeof(UInt32) {
      switch endianness {
        case .LittleEndian:
          bytes.append(UInt8(myInt >> UInt32(i * 8) & UInt32(0xff)))
        case .BigEndian:
          bytes.append(UInt8(myInt >> UInt32((sizeof(UInt32) - 1 - i) * 8) & UInt32(0xff)))
      }
    }
    self.appendBytes(bytes, length:bytes.count)
  }
}

最佳答案

确保 >> 运算符的两个操作数具有相同类型。我把它们设为 UInt32。

extension NSMutableData {

    enum Endianness {
        case LittleEndian, BigEndian
    }

    func appendUInt32(myInt: UInt32, endianness: Endianness = .LittleEndian) {
        var bytes = UInt8[]()
        for i in 0..sizeof(UInt32) {
            switch endianness {
            case .LittleEndian:
                bytes.append(UInt8(myInt >> UInt32(i)))
            case .BigEndian:
                bytes.append(UInt8(myInt >> UInt32((sizeof(UInt32) - 1 - i))))
            }
        }
        self.appendBytes(bytes, length:bytes.count)
    }
}

关于ios - 如何将 UInt32 转换为 UInt8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24481538/

相关文章:

ios - Swift 3 - 类型 'Any' 没有下标成员

ios - 隐藏/显示 UITabBarController 的 .tabBar(用于 Root View Controller )

ios - Codables 错误与 Alamofire "Cannot convert value of type ' [字符串 : Any ]' to expected argument type ' Data'"

ios - 如何通过 swift 3 设置导航 TitleView 和截断标签的宽度

Swift 包管理器 - 类型 'Bundle' 没有成员 “module” 错误

ios - iphone接到电话时如何获取号码

ios - 在后台下载期间未调用我的 NSURLSessionDelegate 方法

iphone - 在 Xcode 4.2 中使用 GPX 路线或轨道进行测试

ios - 如何从不同层次的JSON对象中拉取数据

ios - 如何在 swift 4 的 IBInspectable 中将 Radius 的某些边缘转角?