纯Swift中一个Character的二进制值

时间:2016-02-08 10:00:12

标签: swift binary character

我需要转换二进制字符串中的字符。

Ex:C = 34 =“1000011”

我正在进行的工作看起来像这样。它仅适用于“C”字符:

import Foundation

func charToBin(c:Character) -> String {
    let binaire = 34
    return String(binaire, radix: 2)
}

let c:Character = "C"
let b = charToBin(c)

1 个答案:

答案 0 :(得分:2)

感谢您的帮助:

我用这段代码解决了我的问题:

func stringToBinaryString (myString:String) -> String {

    // Array of characters
    let characterArray = [Character](myString.characters)

    // Array of asccii value
    let asciiArray = characterArray.map({String($0).unicodeScalars.first!.value})

    // Array of binary value
    let binaryArray = asciiArray.map ({ String($0, radix: 2)})

    // Reduce in a String
    let r = binaryArray.reduce("",combine: {$0 + " " + $1})

    return r
}

// Sample use :
let r = stringToBinaryString("CC")