Skip to content

Instantly share code, notes, and snippets.

@ole ole/load-misaligned.swift
Last active Jun 25, 2019

Embed
What would you like to do?
Load misaligned data from a blob of bytes. I don't know if this is correct.
import Foundation
let data = Data([0, 0, 0, 0, 0, 0x11, 0x22, 0x33, 0x44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
data.count
extension UnsafeRawBufferPointer {
func loadUnaligned<T>(fromByteOffset offset: Int, as: T.Type) -> T {
// Allocate correctly aligned memory and copy bytes there
let alignedPointer = UnsafeMutableRawPointer.allocate(byteCount: MemoryLayout<T>.stride, alignment: MemoryLayout<T>.alignment)
defer {
alignedPointer.deallocate()
}
alignedPointer.copyMemory(from: baseAddress!.advanced(by: offset), byteCount: MemoryLayout<T>.size)
return alignedPointer.load(as: T.self)
}
}
// Load unaligned big-endian UInt32
let uint32 = data.withUnsafeBytes { bytes in
bytes.loadUnaligned(fromByteOffset: 5, as: UInt32.self).bigEndian
}
print(uint32) // → 287454020
print(String(uint32, radix: 16)) // → "11223344"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.