From 58c14c18705dfbb26e69cdaf268401c063be8fef Mon Sep 17 00:00:00 2001 From: Timofey Solomko Date: Mon, 24 Oct 2016 20:20:48 +0300 Subject: [PATCH] Added some extensions to Data to allow getting misaligned bytes. --- Sources/DataExtension.swift | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/Sources/DataExtension.swift b/Sources/DataExtension.swift index 8d79a3df..97cb1eb1 100644 --- a/Sources/DataExtension.swift +++ b/Sources/DataExtension.swift @@ -35,5 +35,27 @@ extension Data { func byte(at index: Data.Index) -> UInt8 { return Data(self[index]).to(type: UInt8.self) } + + func byte(at index: Data.Index, withShift shift: Int) -> UInt8 { + precondition(shift >= 0 && shift < 8, "Shift must be between 0 and 7 (included).") + let firstPart = self.byte(at: index) + let secondPart = self.byte(at: index + 1) + let convShift = UInt8(truncatingBitPattern: shift) + let result: UInt8 = (firstPart << convShift) | (secondPart >> (8 - convShift)) + return result + } + + func bytes(from range: Range, withShift shift: Int) -> [UInt8] { + precondition(shift >= 0 && shift < 8, "Shift must be between 0 and 7 (included).") + let bytesArray = self.bytes(from: range.lowerBound..> (8 - convShift))) + } + return resultArray + } }