Skip to content

Instantly share code, notes, and snippets.

@kimjj81
Last active June 25, 2024 17:43
Show Gist options
  • Save kimjj81/aadf55fc591220afdc8450452c2ea21d to your computer and use it in GitHub Desktop.
Save kimjj81/aadf55fc591220afdc8450452c2ea21d to your computer and use it in GitHub Desktop.
Convert UInt to UInt8(byte) Array in swift.
protocol UIntToBytesConvertable {
var toBytes: [UInt8] { get }
}
extension UIntToBytesConvertable {
func toByteArr<T: BinaryInteger>(endian: T, count: Int) -> [UInt8] {
var _endian = endian
let bytePtr = withUnsafePointer(to: &_endian) {
$0.withMemoryRebound(to: UInt8.self, capacity: count) {
UnsafeBufferPointer(start: $0, count: count)
}
}
return [UInt8](bytePtr)
}
}
extension UInt16: UIntToBytesConvertable {
var toBytes: [UInt8] {
if CFByteOrderGetCurrent() == Int(CFByteOrderLittleEndian.rawValue) {
return toByteArr(endian: self.littleEndian,
count: MemoryLayout<UInt16>.size)
} else {
return toByteArr(endian: self.bigEndian,
count: MemoryLayout<UInt16>.size)
}
}
}
extension UInt32: UIntToBytesConvertable {
var toBytes: [UInt8] {
if CFByteOrderGetCurrent() == Int(CFByteOrderLittleEndian.rawValue) {
return toByteArr(endian: self.littleEndian,
count: MemoryLayout<UInt32>.size)
} else {
return toByteArr(endian: self.bigEndian,
count: MemoryLayout<UInt32>.size)
}
}
}
extension UInt64: UIntToBytesConvertable {
var toBytes: [UInt8] {
if CFByteOrderGetCurrent() == Int(CFByteOrderLittleEndian.rawValue) {
return toByteArr(endian: self.littleEndian,
count: MemoryLayout<UInt64>.size)
} else {
return toByteArr(endian: self.bigEndian,
count: MemoryLayout<UInt64>.size)
}
}
}
@andrellaflame
Copy link

Another way to convert UInt to UInt8 is to shift bits. It normally works faster that unsafe pointer

extension UInt16 {
    /// Convert a UInt16 to an array of UInt8.
    /// - Returns: An array of UInt8 representing the UInt16 value.
    var toUInt8: [UInt8] {
        return [
            UInt8(self >> 8),
            UInt8(self & 0xff)
        ]
    }
}

extension UInt32 {
    /// Convert a UInt32 to an array of UInt8.
    /// - Returns: An array of UInt8 representing the UInt32 value.
    var toUInt8: [UInt8] {
        return [
            UInt8((self >> 24) & 0xff),
            UInt8((self >> 16) & 0xff),
            UInt8((self >> 8) & 0xff),
            UInt8(self & 0xff)
        ]
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment