How to convert a binary to decimal in Swift?
Asked Answered
E

4

33

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,

Envelopment answered 6/11, 2014 at 22:32 Comment(3)
Not duplicate; the reverse: #26181721Bonar
Post your Swift code, leaving the bits out that you don't know how to do.Suicide
What binary representation do you have?Burtburta
R
58

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
Radar answered 7/11, 2014 at 22:11 Comment(5)
As fun as the other solutions are, using a lib is the right answer.Slugabed
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.Sure
@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.Radar
@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.Sure
As much as I appreciate the answer. The question was for Decimal. How is "Int" considered a Decimal ?Ossify
P
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
Perilous answered 7/11, 2014 at 22:44 Comment(0)
W
4

binary is built-in to swift using 0b prefix

println( 0b11001 ) // Output: 25
Westlund answered 10/12, 2014 at 9:27 Comment(0)
J
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
Janis answered 7/11, 2014 at 0:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.