0

I use following function to implement Int to UInt8[4] converter:

    func toByteArray(var value: Int) -> [UInt8] {
    var msgLength = [UInt8](count: 4, repeatedValue: 0)

    for i in 0...3 {
        msgLength[i] = UInt8(0x0000FF & value >> Int((3 - i) * 8))
    }
    return msgLength
    }

How to implement Int to UInt8[4]?

fcbflying
  • 693
  • 1
  • 7
  • 23
  • You could refer to [this](http://stackoverflow.com/questions/26953591/how-to-convert-a-double-into-a-byte-array-in-swift) SO link – R P Dec 08 '15 at 04:59

1 Answers1

0

See this answer:

How to convert a type to/from a byte array

func toByteArray( value: Int) -> [UInt8] {
    var msgLength = [UInt8](count: 4, repeatedValue: 0)

    for i in 0...3 {
        msgLength[i] = UInt8(0x0000FF & value >> Int((3 - i) * 8))
    }
    return msgLength
}

// call your function to generate the byte array.  Reverse the order
// since fromByteArray wants them in the reverse (little endian) order    
let b = Array(toByteArray(1234567890).reverse())

func fromByteArray<T>(value: [UInt8], _: T.Type) -> T {
    return value.withUnsafeBufferPointer {
        return UnsafePointer<T>($0.baseAddress).memory
    }
}

let i = fromByteArray(b, Int32.self)
print(i) // 1234567890
Community
  • 1
  • 1
vacawama
  • 150,663
  • 30
  • 266
  • 294