Skip to content

Instantly share code, notes, and snippets.

@Cosmo
Last active March 19, 2019 01:17
Show Gist options
  • Save Cosmo/b6ceedf7e384a7de06eb7f67ce1c2bbb to your computer and use it in GitHub Desktop.
Save Cosmo/b6ceedf7e384a7de06eb7f67ce1c2bbb to your computer and use it in GitHub Desktop.
Shift [UInt8] / Data in Swift
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