kgreenek
kgreenek

Reputation: 5024

How to cast UInt32 to UInt8

I need to append a UInt32 to a NSMutableData object in swift. The problem is, I can't figure out how to access a particular byte in the int.

Here is what I have tried:

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)
  }
}

This throws a compiler exception that I can't cast from a UInt32 to a UInt8. Is there an easy way to simply access a byte in a UInt32?

EDIT: Summarizing final solution from the comments:

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)
  }
}

Upvotes: 2

Views: 2427

Answers (1)

Connor
Connor

Reputation: 64634

Make sure both operands of your >> operator are of the same type. I made them 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)
    }
}

Upvotes: 3

Related Questions