Swift中将数字转换成16进制和2进制都非常的简单:
var convert=String(10,radix:2)
convert=String(16,radix:16)
print("\(convert)")
同样的也可以将二进制数字转换成十进制:
二进制转换
func binaryPosition(position:NSInteger)->NSInteger {
var result=1
for _ in 0..<position {
result = result*2
}
return result
}
func convertBinaryToDecimal(binaryNumber:String)->NSInteger {
var result=0
var temp:NSInteger
var power:NSInteger
for index in 0..<binaryNumber.characters.count {
temp = Int(binaryNumber[index] as String)!
power = binaryNumber.characters.count-1-index
result = result+temp*binaryPosition(power)
}
return result
}
func convertNumberToHex(number:NSInteger)->String{
if number<=0 {
return "0"
}
var result:String = ""
var num = number
while(num != 0){
result=String(num%2)+result
num=num/2
}
return result
}
测试代码:
var binaryNumber="1111"
var resultValue=convertBinaryToDecimal(binaryNumber)
print("\(binaryNumber)的值:\(resultValue)")
var binaryHex=convertNumberToHex(resultValue)
print("FlyElephant:\(binaryHex)")
16进制转换
16进制的转换成数字需要自己定义函数实现,实现方式如下:
func converHexToDecimal(number:String,radix:NSInteger)->NSInteger? {
let digits = "0123456789abcdefghijklmnopqrstuvwxyz"
var result=0
for digit in number.lowercaseString.characters {
if let range = digits.rangeOfString(String(digit)) {
let index: Int = digits.startIndex.distanceTo(range.startIndex)
if index>radix {
return nil
}
result=result*radix+index
}
}
return result
}
var convert=String(100,radix:16)
print("FlyElephant-100的进制值:\(convert)")
var decimalNumber=converHexToDecimal(convert, radix: 16)
print("FlyElephant-\(convert)的十进制\(decimalNumber!)")