Last active
June 25, 2019 21:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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