Split UInt32 into [UInt8] in swift
I want to add UInt32
to the buffer the byte I am using [UInt8]
. There is a convenient ByteBuffer class in java that has methods like putInt () for cases in exactly the same way. How can this be done quickly?
I think I could solve it like this:
let example: UInt32 = 72 << 24 | 66 << 16 | 1 << 8 | 15
var byteArray = [UInt8](count: 4, repeatedValue: 0)
for i in 0...3 {
byteArray[i] = UInt8(0x0000FF & example >> UInt32((3 - i) * 8))
}
Is this a rather verbose, albeit easier way?
+3
source to share
5 answers
Your loop is more compactly written as
let byteArray = 24.stride(through: 0, by: -8).map {
UInt8(truncatingBitPattern: example >> UInt32($0))
}
Alternatively, create UnsafeBufferPointer
and convert this to an array:
let example: UInt32 = 72 << 24 | 66 << 16 | 1 << 8 | 15
var bigEndian = example.bigEndian
let bytePtr = withUnsafePointer(&bigEndian) {
UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: sizeofValue(bigEndian))
}
let byteArray = Array(bytePtr)
print(byteArray) // [72, 66, 1, 15]
Update for Swift 3 (Xcode 8 beta 6):
var bigEndian = example.bigEndian
let count = MemoryLayout<UInt32>.size
let bytePtr = withUnsafePointer(to: &bigEndian) {
$0.withMemoryRebound(to: UInt8.self, capacity: count) {
UnsafeBufferPointer(start: $0, count: count)
}
}
let byteArray = Array(bytePtr)
+8
source to share
Improved @ Martin R's answer. Worked on UInt16, UInt32 and UInt64:
protocol UIntToBytesConvertable {
var toBytes: [Byte] { get }
}
extension UIntToBytesConvertable {
func toByteArr<T: Integer>(endian: T, count: Int) -> [Byte] {
var _endian = endian
let bytePtr = withUnsafePointer(to: &_endian) {
$0.withMemoryRebound(to: Byte.self, capacity: count) {
UnsafeBufferPointer(start: $0, count: count)
}
}
return [Byte](bytePtr)
}
}
extension UInt16: UIntToBytesConvertable {
var toBytes: [Byte] {
return toByteArr(endian: self.littleEndian,
count: MemoryLayout<UInt16>.size)
}
}
extension UInt32: UIntToBytesConvertable {
var toBytes: [Byte] {
return toByteArr(endian: self.littleEndian,
count: MemoryLayout<UInt32>.size)
}
}
extension UInt64: UIntToBytesConvertable {
var toBytes: [Byte] {
return toByteArr(endian: self.littleEndian,
count: MemoryLayout<UInt64>.size)
}
}
+3
source to share
Improved @ Martin R's answer.
func toByteArrary<T>(value: T) -> [UInt8] where T: UnsignedInteger, T: FixedWidthInteger{
var bigEndian = value.bigEndian
let count = MemoryLayout<T>.size
let bytePtr = withUnsafePointer(to: &bigEndian) {
$0.withMemoryRebound(to: UInt8.self, capacity: count) {
UnsafeBufferPointer(start: $0, count: count)
}
}
return Array(bytePtr)
}
0
source to share