Non-decimal radices/Convert: Difference between revisions

(Hello, I'm a 12 year old boy. I have posted the Scratch solution to this problem online.)
Line 1,969:
 
=={{header|Swift}}==
Converting integer to string is easy:
<lang swift>println(String(26, radix: 16)) // prints "1a"</swiftlang>
 
Converting from string to integer is harder:
<lang swift>funcimport digit2int(c: UnicodeScalar) -> Int {Darwin
switch c {
case "0"..."9":
return c.value - "0".value
case "a"..."z":
return c.value - "a".value + 10
case "A"..."Z":
return c.value - "A".value + 10
default:
fatalError("invalid digit")
}
}
func string2int(s: String, radix: Int) -> Int {
return reduce(lazystrtol(s.unicodeScalars).map(digit2int), 0){$0 *nil, Int32(radix + $1}))
// there is also strtoul() for UInt, and strtoll() and strtoull() for Int64 and UInt64, respectively
}
println(string2int("1a", 16)) // prints "26"</lang>
Anonymous user