请考虑使用以下代码段将十六进制Character
转换为整数值
extension Character {
var hexValue : UInt {
let zero : Character = "0"
let nine : Character = "9"
let a : Character = "a"
let f : Character = "f"
let A : Character = "A"
let F : Character = "F"
if self >= zero && self <= nine {
return self - zero
}
if self >= a && self <= f {
return self - a + 10
}
if self >= A && self <= F {
return self - A + 10
}
return 0
}
}
不幸的是,Swift编译器不喜欢+
上的-
/ Character
操作。
如何在Swift中对字符进行算术运算?
答案 0 :(得分:2)
当我在Swift标题周围挖掘时,我找到了答案。我们可以使用UnicodeScalar
,例如:
UnicodeScalar("a").value
value
将为您提供字符整数值
要转换任意Character
,您可以执行此操作
let s = String(myChar).unicodeScalars
let i = scalars[s.startIndex].value
答案 1 :(得分:0)
尝试NSScanner:
var hexChar = "A"
var hexValue:UInt32 = 0
let scanner = NSScanner(string: hexChar)
scanner.scanHexInt(&hexValue)
println(hexValue) // prints 10