3

Hi I am trying to convert an octal number to decimal in swift. What would be the easiest way to do this?

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
user190494
  • 509
  • 2
  • 8
  • 20
  • Possible duplicate of [Dealing with Octal numbers in swift](http://stackoverflow.com/questions/28745242/dealing-with-octal-numbers-in-swift) – pableiros Jul 19 '16 at 15:46

2 Answers2

6

From Octal to Decimal

There is a specific Int initializer for this

let octal = 10
if let decimal = Int(String(octal), radix: 8) {
    print(decimal) // 8
}

From Decimal to Octal

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.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • Awesome, do you know how you would do vice versa? Thanks :) – user190494 Jul 19 '16 at 15:52
  • @user190494 Going from decimal to octal? – Alexander Jul 19 '16 at 15:55
  • yup, decimal to octal. Thanks bro. – user190494 Jul 19 '16 at 15:55
  • 3
    Keep in mind: Numbers don't have a radix. The radix is necessary to specify a way of formatting a number for humans to interpret. The magnitudes expressed by these string representations exist distinctly from all any radixes and string representations. – Alexander Jul 19 '16 at 16:10
  • 1
    @appzYourLife I'm fairly certain that `Int` initializer can fail for string representations of number with more exotic radixes. You don't need that `Int` conversion anyway, you can just print the result of the `String(_:, radix:)` call – Alexander Jul 19 '16 at 16:11
  • @AMomchilov: yes it makes sense, I added a note to my answer thanks. – Luca Angeletti Jul 19 '16 at 16:22
1

you can convert from octal to decimal easily. Swift supports octal syntax natively. You have to write "0o" before the octal number.

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.

Here is the documentation's reference.

I hope it helps you