如何在 Swift 中从八进制转换为十进制
How to convert from Octal to Decimal in Swift
您好,我正在尝试将 swift 中的八进制数转换为十进制数。最简单的方法是什么?
从八进制到十进制
这里有一个特定的 Int
初始值设定项
let octal = 10
if let decimal = Int(String(octal), radix: 8) {
print(decimal) // 8
}
从十进制到八进制
let decimal = 8
if let octal = Int(String(decimal, radix: 8)) {
print(octal) // 10
}
Note 1: Please pay attention: parenthesis are different in the 2 code snippets.
Note 2: Int
initializer can fail for string representations of number with more exotic radixes. Please read the comment by @AMomchilov below.
您可以轻松地将八进制转换为十进制。 Swift 原生支持八进制语法。八进制数前必须写“0o”
let number = 0o10
print(number) // it prints the number 8 in decimal
Integer Literals
Integer literals represent integer values of unspecified precision. By
default, integer literals are expressed in decimal; you can specify an
alternate base using a prefix. Binary literals begin with 0b, octal
literals begin with 0o, and hexadecimal literals begin with 0x.
这里是 documentation's reference.
希望对你有帮助
您好,我正在尝试将 swift 中的八进制数转换为十进制数。最简单的方法是什么?
从八进制到十进制
这里有一个特定的 Int
初始值设定项
let octal = 10
if let decimal = Int(String(octal), radix: 8) {
print(decimal) // 8
}
从十进制到八进制
let decimal = 8
if let octal = Int(String(decimal, radix: 8)) {
print(octal) // 10
}
Note 1: Please pay attention: parenthesis are different in the 2 code snippets.
Note 2:
Int
initializer can fail for string representations of number with more exotic radixes. Please read the comment by @AMomchilov below.
您可以轻松地将八进制转换为十进制。 Swift 原生支持八进制语法。八进制数前必须写“0o”
let number = 0o10
print(number) // it prints the number 8 in decimal
Integer Literals
Integer literals represent integer values of unspecified precision. By default, integer literals are expressed in decimal; you can specify an alternate base using a prefix. Binary literals begin with 0b, octal literals begin with 0o, and hexadecimal literals begin with 0x.
这里是 documentation's reference.
希望对你有帮助