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

Philippe Hausler phausler at apple.com
Sun Jun 25 21:53:35 CDT 2017


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



More information about the swift-users mailing list