32

I am looking for a simple way to convert a binary number in decimal in Swift. For example, "10" in binary becomes "2" in decimal.

Thanks,

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Geanderson Esteves
  • 463
  • 1
  • 4
  • 9

4 Answers4

56

Update for Swift 2: All integer types have an

public init?(_ text: String, radix: Int = default)

method now, which converts a string to an integer according to a given base:

let binary = "11001"
if let number = Int(binary, radix: 2) { 
    print(number) // Output: 25
}

(Previous answer:) You can simply use the BSD library function strtoul(), which converts a string to a number according to a given base:

let binary = "11001"
let number = strtoul(binary, nil, 2)
println(number) // Output: 25
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    As fun as the other solutions are, using a lib is the right answer. – sherb Nov 07 '14 at 22:18
  • Can you tell me how can I do this for very big binary string. For example a binary string like this : "1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010". Current solution can't convert this number which is pretty long. – Saleh Masum Mar 13 '20 at 08:08
  • @SalehMasum: The largest integer type in Swift is UInt64. There is no integer type which can hold a 100 bit number. You can split the string into smaller chunks, or look for a “big integer” library. – Martin R Mar 13 '20 at 08:16
  • @MartinR Thank you for the nice explanation. Now I understand it why it does not work. I need to have a look on some thing like BigInteger. – Saleh Masum Mar 13 '20 at 08:25
  • As much as I appreciate the answer. The question was for **Decimal**. How is "Int" considered a Decimal ? – iOS Blacksmith Sep 06 '22 at 09:17
23

Update: Xcode 7.2 • Swift 2.1.1

You can implement Martin R's Answer making an extension using C++ function called strtoul as follow:

extension String {
    var hexaToInt      : Int    { return Int(strtoul(self, nil, 16))      }
    var hexaToDouble   : Double { return Double(strtoul(self, nil, 16))   }
    var hexaToBinary   : String { return String(hexaToInt, radix: 2)      }
    var decimalToHexa  : String { return String(Int(self) ?? 0, radix: 16)}
    var decimalToBinary: String { return String(Int(self) ?? 0, radix: 2) }
    var binaryToInt    : Int    { return Int(strtoul(self, nil, 2))       }
    var binaryToDouble : Double { return Double(strtoul(self, nil, 2))   }
    var binaryToHexa   : String { return String(binaryToInt, radix: 16)  }
}

extension Int {
    var binaryString: String { return String(self, radix: 2)  }
    var hexaString  : String { return String(self, radix: 16) }
    var doubleValue : Double { return Double(self) }
}

"ff".hexaToInt              // "255"
"ff".hexaToDouble           // "255.0"
"ff".hexaToBinary           // "11111111"
"255".decimalToHexa         // "ff"
"255".decimalToBinary       // "11111111"
"11111111".binaryToInt      // "255"
"11111111".binaryToDouble   // "255.0"
"11111111".binaryToHexa     // "ff"
255.binaryString            // "11111111"
255.hexaString              // "ff"
255.doubleValue             // 255.0
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
4

binary is built-in to swift using 0b prefix

println( 0b11001 ) // Output: 25
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
ziligy
  • 1,447
  • 16
  • 10
3

There may be a built-in to do this, but writing the code yourself isn't hard:

func parseBinary(binary: String) -> Int? {
    var result: Int = 0

    for digit in binary {
        switch(digit) {
            case "0": result = result * 2
            case "1": result = result * 2 + 1
            default: return nil
        }
    }
    return result
}

The function returns an (optional) Int. If you want to get a string instead, you can do the following:

String(parseBinary("10101")!)
-> "21"

Note the forced unwrapping (!) If the string you provide contains anything other than 0's or 1's, the function returns nil and this expression will blow up.

Or, taking a cue from Leonardo, you can build this as an extension to string:

extension String {
    func asBinary() -> Int? {
        var result: Int = 0

        for digit in self {
            switch(digit) {
                case "0": result = result * 2
                case "1": result = result * 2 + 1
                default: return nil
            }
        }
        return result
    }
}

"101".asBinary()!
-> 5
Todd Agulnick
  • 1,945
  • 11
  • 10