iLandes February 2016

Binary value of a Character in pure Swift

I need to convert a character in its binary string.

Ex : C = 34 = "1000011"

My work in progress look like this. It's work only for "C" character :

import Foundation

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

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

Answers


iLandes February 2016

Thank you for your help :

I solved my problem with this code :

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

Post Status

Asked in February 2016
Viewed 2,106 times
Voted 13
Answered 1 times

Search




Leave an answer