[swift-users] Extracting arbitrary types (e.g. UInt16) out of Data
Charles Srstka
cocoadev at charlessoft.com
Mon Jun 26 01:11:00 CDT 2017
> On Jun 26, 2017, at 12:00 AM, Roderick Mann via swift-users <swift-users at swift.org> wrote:
>
> I mean, it's as straightforward as my example. I have a Data of arbitrary size (anywhere from 3 to 29 bytes, let's say). The last two bytes form a UInt16 CRC. I need to get those last two out and compare them against the CRC I compute for the rest of the bytes.
>
> Having said that, I just used withUnsafeBytes() and grabbed the last two bytes, and assembled them into a UInt16 with shift and or.
>
> I'd like to be able to do something like value<Double>(at: 3), though.
You kinda can, although it’s a bit more verbose:
let crc = myData[(myData.endIndex - 2)…].withUnsafeBytes { UInt16(littleEndian: $0.pointee) }
If you look at the source, withUnsafeBytes calls withMemoryRebound with the inferred generic type (UInt16 in this case), so I think this should be safe.
Charles
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170626/a8a89133/attachment.html>
More information about the swift-users
mailing list