Is there a way to convert a string to binary in Swift?
Found this link on SO but it only handles converting decimals. I'm trying to convert special characters and letters as well.
Tried building an array of known ASCII characters and comparing them(worked for letters) but ran into problems comparing the special characters.
Appreciating your responses.
Use func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Example:
Swift 5
let string = "The string"
let binaryData = Data(string.utf8)
Swift 3
let string = "The string"
let binaryData: Data? = string.data(using: .utf8, allowLossyConversion: false)
EDIT: Or wait, do you need binary representation of you data or string of 0/1?
EDIT: For string of 0/1 use something like:
let stringOf01 = binaryData?.reduce("") { (acc, byte) -> String in
acc + String(byte, radix: 2)
}
EDIT: Swift 2
let binaryData = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
Swift 5:
This will add a String Extension
extension String {
func stringToBinary() -> String {
let st = self
var result = ""
for char in st.utf8 {
var tranformed = String(char, radix: 2)
while tranformed.count < 8 {
tranformed = "0" + tranformed
}
let binary = "\(tranformed) "
result.append(binary)
}
return result
}
}
This is going to return a string of 0s and 1s separated by spaces. You can modify it to return an array if needed.
Implementation:
let string = "Hello World"
let newString = string.stringToBinary()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With