6

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.

1
  • I want to break a string down into 1's and zero's no matter what the string contains. Then from there I will move onto phase 2... Commented Oct 20, 2016 at 12:59

3 Answers 3

10

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Yes was trying to get 0101010 kinda style
This works great for swift3 thank you :) , as a matter of public interest do you perhaps know how it would have been done in swift2 as well?
@AMAN77, Data -> NSData, .data(using:… -> .dataUsing(…, just rollback names.
Added some swift 2 code to your answer but have been struggling to do the 0/1 string part.
Note that, at least the swift 3 version, doesn't show the leading zeros.
3

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()

Comments

1

For Swift 5, you can add a String Extension like that:

extension String {
    var hexaToBinary: String {
        return hexaToBytes.map {
            let binary = String($0, radix: 2)
            return repeatElement("0", count: 8-binary.count) + binary
        }.joined()
    }

    private var hexaToBytes: [UInt8] {
        var start = startIndex
        return stride(from: 0, to: count, by: 2).compactMap { _ in
            let end = index(after: start)
            defer { start = index(after: end) }
            return UInt8(self[start...end], radix: 16)
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.