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

Roderick Mann rmann at latencyzero.com
Mon Jun 26 00:00:46 CDT 2017


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.


> On Jun 25, 2017, at 19:53 , Philippe Hausler <phausler at apple.com> wrote:
> 
> There are probably a number of ways that would do what you need. I would need a bit more context or examples of what you are doing already to comment. But if I had those parameters to work with I would use copyBytes into the address of the target you are wanting to read.
> 
> There are some cases that might be improved when we add the UnsafeRawBuferPointer apis to Data.
> 
> Can you share a small sample of what you have already?
> 
>> On Jun 25, 2017, at 5:37 PM, Rick Mann via swift-users <swift-users at swift.org> wrote:
>> 
>> I continue to struggle with the "proper" and most efficient way to do things with Data.
>> 
>> In this case, I have a set of bytes received over a serial port in a Data. The last two bytes are a (big- or little-endian) UInt16 CRC. However, there maybe an odd or even number of bytes in the Data before these last two bytes, so I can't just use withUnsafePointer<UInt16>.
>> 
>> I'd also like to avoid unnecessary copying of the data. All of it is immutable for the purposes of this problem.
>> 
>> How can I get the UInt16 that starts at byte X in a Data? Same goes for Double or Int32 or whatever.
>> 
>> If the endianness needs to change, I can do that swapping after I've gotten the typed value out.
>> 
>> -- 
>> Rick Mann
>> rmann at latencyzero.com
>> 
>> 
>> _______________________________________________
>> swift-users mailing list
>> swift-users at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-users
> 


-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list