Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to binary in swift?

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.

like image 713
AMAN77 Avatar asked Oct 20 '16 12:10

AMAN77


2 Answers

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)
like image 78
user28434'mstep Avatar answered Sep 28 '22 02:09

user28434'mstep


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()
like image 41
Yush Raj Kapoor Avatar answered Sep 28 '22 00:09

Yush Raj Kapoor