Last active
March 19, 2019 01:17
-
-
Save Cosmo/b6ceedf7e384a7de06eb7f67ce1c2bbb to your computer and use it in GitHub Desktop.
Shift [UInt8] / Data in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Data { | |
/// Returns a new `Data` shifted by the number of given bits. | |
/// | |
/// - parameter bits: Number of bits the data to be shifted. | |
/// - returns: The shifted data. | |
func shifted(byBits bits: Int) -> Data { | |
let bitWidth = UInt8.bitWidth | |
var previousByte = UInt8() | |
return Data(bytes: self.shifted(byBytes: bits / bitWidth).map { | |
let result: UInt8 = ($0 >> (bits % bitWidth)) | (previousByte << (bits % bitWidth)) | |
previousByte = $0 | |
return result | |
}) | |
} | |
/// Returns a new `Data` shifted by the number of given bytes. | |
/// | |
/// - parameter bytes: Number of bytes the data to be shifted. | |
/// - returns: The shifted data. | |
func shifted(byBytes bytes: Int) -> Data { | |
return self.dropLast(bytes) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment