Skip to content

Instantly share code, notes, and snippets.

@pofat
Created November 1, 2016 02:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pofat/6ae0c2626660741234f159c60f51af91 to your computer and use it in GitHub Desktop.
Save pofat/6ae0c2626660741234f159c60f51af91 to your computer and use it in GitHub Desktop.
A method to retrieve byte array and bit array from Data in Swift 3
// Using UInt8 as Byte
typealias Byte = UInt8
enum Bit: Int {
case zero, one
}
extension Data {
var bytes: [Byte] {
var byteArray = [UInt8](repeating: 0, count: self.count)
self.copyBytes(to: &byteArray, count: self.count)
return byteArray
}
}
extension Byte {
var bits: [Bit] {
let bitsOfAbyte = 8
var bitsArray = [Bit](repeating: Bit.zero, count: bitsOfAbyte)
for (index, _) in bitsArray.enumerated() {
// Bitwise shift to clear unrelevant bits
let bitVal: UInt8 = 1 << UInt8(bitsOfAbyte - 1 - index)
let check = self & bitVal
if check != 0 {
bitsArray[index] = Bit.one
}
}
return bitsArray
}
}
// Example
let originString = "hello world"
let strData = originString.data(using: .utf8)!
print(strData.bytes)
print(strData.bytes.first?.bits)
@WebberLai
Copy link

is it possible return bits array to bytes ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment