如何将UInt32转换为UInt8

时间:2014-06-30 00:33:00

标签: ios swift

我需要在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)
  }
}

1 个答案:

答案 0 :(得分:3)

确保>>运算符的两个操作数都属于同一类型。我把它们变成了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)
    }
}