Home > other >  I want create a program using closure that will return the equivalent binary value of the given arra
I want create a program using closure that will return the equivalent binary value of the given arra

Time:10-20

This is my code

create a program using closure that will return the equivalent binary value of the given array hexadecimal value.

let hexBin = [0:"0000", 1:"0001", 2:"0010", 3:"0011", 4:"0100", 5:"0101", 6:"0110", 7:"0111", 8:"1000", 9:"1001", A:"1010", B:"1011", C:"1100", D:"1101", E:"1110", F:"1111"]

var myNumArr = [123, ABC, 4DE, F05]

let myCovertedValue = myNumArr.map{

num -> String in

    var num = num

    var output = ""

    repeat {

        output = hexBin[num % 10]!   output

        num /= 10

    } while(num > 0)

    return output

}

print(myCovertedValue)

Output should be like this

["000100100011", "101010111100", "010011011110", "111100000101"]

The number 123 is working but I don't know how will it works in letter only and number in mix.

CodePudding user response:

func hexToBinary(array : [String]) -> [Any]{
    return array.map{ String(Int($0, radix: 16)!, radix: 2).pad(with: "0", toLength: 12)}
}

extension String {
    func pad(with character: String, toLength length: Int) -> String {
        let padCount = length - self.count
        guard padCount > 0 else { return self }

        return String(repeating: character, count: padCount)   self
    }
}

print(hexToBinary(array: myNumArr)) //["000100100011", "101010111100", "010011011110", "111100000101"]
  • Related