<div dir="ltr">yikes there’s no less verbose way to do that? and if the type isn’t an integer there’s no way to avoid the default initialization? Can this be done with opaques or something?<br></div><div class="gmail_extra"><br><div class="gmail_quote">On Wed, Nov 8, 2017 at 7:04 PM, Johannes Weiß <span dir="ltr"><<a href="mailto:johannesweiss@apple.com" target="_blank">johannesweiss@apple.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">Hi Kelvin,<br>
<div><div class="h5"><br>
> On 8 Nov 2017, at 4:54 pm, Kelvin Ma via swift-users <<a href="mailto:swift-users@swift.org">swift-users@swift.org</a>> wrote:<br>
><br>
> According to the docs, the load(fromByteOffset:as:) method requires the instance to be “properly aligned” Does that mean if I have raw data meant to be interpreted as<br>
><br>
> 0 1 2 3 4 5 6<br>
> [ Int8 | Int16 | Int16 | Int8 | Int8 ]<br>
><br>
><br>
> i can’t just load the Int16 from byte offset 1?<br>
<br>
</div></div>you can't just dereference that pointer as an Int16 (in any language) without causing UB but it's not really an issue, just do this (assuming `ptr` is the pointer into your data and `index` is the index to where your Int16 lives):<br>
<br>
<br>
var value: Int16 = 0<br>
withUnsafeMutableBytes(of: &value) { valuePtr in<br>
valuePtr.copyBytes(from: UnsafeRawBufferPointer(start: ptr.baseAddress!.advanced(by: index),<br>
count: MemoryLayout<Int16>.size))<br>
}<br>
<br>
you can have the whole thing generic too for <T: FixedWidthInteger><br>
<br>
var value: T = 0<br>
withUnsafeMutableBytes(of: &value) { valuePtr in<br>
valuePtr.copyBytes(from: UnsafeRawBufferPointer(start: ptr.baseAddress!.advanced(by: index),<br>
count: MemoryLayout<T>.size))<br>
}<br>
<br>
-- Johannes<br>
<br>
<br>
> ______________________________<wbr>_________________<br>
> swift-users mailing list<br>
> <a href="mailto:swift-users@swift.org">swift-users@swift.org</a><br>
> <a href="https://lists.swift.org/mailman/listinfo/swift-users" rel="noreferrer" target="_blank">https://lists.swift.org/<wbr>mailman/listinfo/swift-users</a><br>
<br>
</blockquote></div><br></div>