I did the following in order to convert an Integer type to an array of smaller (or same size) integer types:
extension FixedWidthInteger {
public func flattened<T: FixedWidthInteger>() -> [T] {
let selfSize = MemoryLayout<Self>.size
let resultSize = MemoryLayout<T>.size
precondition(selfSize >= resultSize,
"Size of result (\(T.self): \(resultSize)) must not be greater than size of field (\(Self.self): \(selfSize))")
return (0 ..< selfSize / resultSize).map {
T(truncatingIfNeeded: self >> Self($0 * T.bitWidth))
}
}
}
let ui32: UInt32 = 0x12345678
let fourBytes: [UInt8] = ui32.flattened()
print(fourBytes.map { String($0, radix: 16) }) // ["78", "56", "34", "12"]
Does something like this already exist, and I just can't find it?
Also, it seems to also work as well as an extension to BinaryInteger. Any good reason to choose one over the other?
Is there a better name? Names can be hard!
Thanks.