Skip to content

Instantly share code, notes, and snippets.

@ole
Last active June 25, 2019 21:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ole/a908c96bd49d48c056605cbf8aa5164f to your computer and use it in GitHub Desktop.
Save ole/a908c96bd49d48c056605cbf8aa5164f to your computer and use it in GitHub Desktop.
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