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

Charles Srstka cocoadev at charlessoft.com
Mon Jun 26 15:43:37 CDT 2017


> On Jun 26, 2017, at 3:41 PM, Roderick Mann <rmann at latencyzero.com> wrote:
> 
>> 
>> On Jun 26, 2017, at 10:20 , Charles Srstka <cocoadev at charlessoft.com <mailto:cocoadev at charlessoft.com>> wrote:
>> 
>> Rats, I was hoping that one of the reasons about being so explicit what we’re going to access and where with bindMemory() and friends would be to take care of these sorts of issues.
>> 
>> In that case, the simplest way to do it is probably just this:
>> 
>> let crc = (UInt16(myData[myData.endIndex]) << 8) | UInt16(myData[myData.endIndex - 1])
>> 
>> (or the reverse, depending on the endianness of the source data)
> 
> Ah. I was doing it like this, but I guess I don't really need to, do I?
> 
>    let count = self.count
>    let ourCRC = self.withUnsafeBytes
>    { (inPtr: UnsafePointer<UInt8>) -> UInt16 in
>        let b1 = UInt16(inPtr[count - 2])
>        let b2 = UInt16(inPtr[count - 1])
>        let b = (b1 << 8) | b2
>        return b
>    }

Doing it via the pointer might be a smidge faster, but I kinda doubt you’ll notice it.

Charles

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170626/10e55209/attachment.html>


More information about the swift-users mailing list