二进制、十进制互转
2022-11-15 本文已影响0人
麦志超
十进制整数 转 二进制数组
func number2BinaryStrList(number: Int) -> [String] {
let binary = String(number, radix: 2)
let str = String(format: "%07d", Int(binary) ?? 0)
var strList = [String]()
for i in str {
strList.append(String(i))
}
return strList
}
举个例子:
print(number2BinaryStrList(number: 12))
输出:["0", "0", "0", "1", "1", "0", "0"]
二进制字符串 转 十进制整数
func binaryStr2Number(str: String) -> Int {
var sum = 0
for i in str {
sum = sum * 2 + (Int((String(i))) ?? 0)
}
return sum
}
举个例子:
print(binaryStr2Number(str: "0001100"))
输出:12
二进制数组 转 十进制整数
func binaryStrList2Number(list: [String]) -> Int {
let reversedList = Array(list.reversed())
var sum = 0
for i in 0 ..< reversedList.count {
let value = pow(2, Double(i)) * (Double(Int(reversedList[i]) ?? 0))
sum += Int(value)
}
return sum
}
举个例子:
print(binaryStrList2Number(list: ["0", "0", "0", "1", "1", "0", "0"]))
输出:12