Convert a String to binary in swift?

时间:2016-10-20 12:44:42

标签: string binary char ascii swift3

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.

3 个答案:

答案 0 :(得分:6)

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)

答案 1 :(得分:1)

对于Swift 5,您可以添加这样的字符串扩展名:

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

答案 2 :(得分:1)

Swift 5:

这将添加一个字符串扩展

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
    }
}

这将返回由空格分隔的 0 和 1 字符串。如果需要,您可以修改它以返回一个数组。

实施:

let string = "Hello World"
let newString = string.stringToBinary()