Convert a String to binary in swift?

ascii, binary, char, string, swift3

Solution

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)

Problem

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.

Original source

Related problems