Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
(→{{header|Go}}: note the limits of the base argument) |
(added swift) |
||
Line 1,964: | Line 1,964: | ||
val it = 42 : int |
val it = 42 : int |
||
</pre> |
</pre> |
||
=={{header|Swift}}== |
|||
Converting integer to string is easy: |
|||
<lang swift>println(String(26, radix: 16)) // prints "1a"</swift> |
|||
Converting from string to integer is harder: |
|||
<lang swift>func digit2int(c: UnicodeScalar) -> Int { |
|||
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 map(s.unicodeScalars, digit2int).reduce(0){$0 * radix + $1} |
|||
} |
|||
println(string2int("1a", 16)) // prints "26"</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |