Created
November 1, 2016 02:38
-
-
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
This file contains 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
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is it possible return bits array to bytes ?