[swift-users] Extracting arbitrary types (e.g. UInt16) out of Data

Roderick Mann rmann at latencyzero.com
Mon Jun 26 04:36:07 CDT 2017


Thanks, I'll give that a try.

> On Jun 25, 2017, at 23:11 , Charles Srstka <cocoadev at charlessoft.com> wrote:
> 
>> 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
> 


-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list