我使用以下函数来实现Int到UInt8 [4]转换器:
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
}
如何实现Int到UInt8 [4]?
答案 0 :(得分:0)
看到这个答案:
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