Why? Swift doesn't have a built-in way of shifting the bits from multiple bytes inside Data.
The below extension on Data allows you to do exactly that:
var exampleData = Data([40, 127, 67]) // ["00101000", "01111111", "01000011"]
// Left shift:
exampleData << 10 // ["11111101", "00001100", "00000000"]
// Left shift and set:
exampleData <<= 10 // ["11111101", "00001100", "00000000"]
exampleData = Data([40, 127, 67]) // ["00101000", "01111111", "01000011"]
// Right shift:
exampleData >>> 10 // ["00000000", "00001010", "00011111"]
// Right shift and set
exampleData >>>= 10 // ["00000000", "00001010", "00011111"]- For left shift use either
<<or<<=. - For right shift use either
>>>or>>>=. Right shifts are always logical right shifts, arithmetic right shifts are not supported. - The above operators don't overwrite the built-in Swift bitwise operators like
<<or<<=. They are only used if the left side of the expression is of typeData.
You can use following function to print the values of Data as binary for testing.
func printData(_ data: Data) {
let result: [String] = data.map { byte in
var byteString = String(byte, radix: 2)
(0..<(8-byteString.count)).forEach { _ in byteString = "0"+byteString }
return byteString
}
print(result)
}
printData(exampleData)