withUnsafeBytes and C Interop
Bridge to C APIs that expect raw bytes.
From Typed to Raw Bytes
Sometimes you need to see a value not as an Int or a struct, but as a sequence of raw bytes — to hash it, write it to a file, or hand it to a C API. withUnsafeBytes gives you exactly that: a temporary view of a value's storage as UInt8.
var value: UInt32 = 0x01020304
withUnsafeBytes(of: &value) { rawBuffer in
print(rawBuffer.count) // 4 bytes
}The UnsafeRawBufferPointer
The closure receives an UnsafeRawBufferPointer — a buffer of bytes with no element type. You index it to read individual UInt8 values. It is read-only; the mutable form is withUnsafeMutableBytes.
var value: UInt32 = 0x01020304
withUnsafeBytes(of: &value) { bytes in
for b in bytes { print(String(format: "%02x", b)) }
}
// Order depends on endiannessAll lessons in this course
- MemoryLayout and Alignment
- UnsafePointer and UnsafeMutablePointer
- Unsafe Buffer Pointers
- withUnsafeBytes and C Interop