提问人:Angelica Clemente 提问时间:10/20/2022 更新时间:10/20/2022 访问量:191
我想创建一个使用闭包的程序,该程序将在 swift 中返回给定数组十六进制值的等效二进制值
I want create a program using closure that will return the equivalent binary value of the given array hexadecimal value in swift
问:
这是我的代码
使用 closure 创建一个程序,该程序将返回给定数组十六进制值的等效二进制值。
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”]
变量 myNumArr = [123, ABC, 4DE, F05]
let myCovertedValue = myNumArr.map{
num -> 字符串 in
var num = num
var output = ""
repeat {
output = hexBin[num % 10]! + output
num /= 10
} while(num > 0)
return output
}
打印(myCovertedValue)
输出应如下所示
["000100100011", "101010111100", "010011011110", "111100000101"]
数字 123 正在工作,但我不知道它将如何仅以字母和混合数字工作。
答:
0赞
udi
10/20/2022
#1
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"]
评论