Convert Binary String to Integer

Swift Binary Representation

How do you convert Binary String to it’s Integer Value?

There are many approaches to convert Binary strings to Integers. One approach could be to iterate through all of the characters in the string and add the value of 2 raised to the power of the index.

Why do I need to convert Binary?

Just for the heck of it, or maybe you might need to convert Hex values to Integers. However, back to the task at hand of converting binary strings, you might have to also include code to check for invalid inputs. A cleverly written algorithm can achieve this in fewer lines of code but all of this can be achieved in practically the minimal lines of code.

Show me the code

func binaryToInt(binaryString: String) -> Int {
  return strtoul(binaryString, nil, 2)
}

binaryToInt("1")             // 1
binaryToInt("10")            // 2
binaryToInt("100")           // 4
binaryToInt("1011")          // 11
binaryToInt("carr0ts12")     // 0

There you have it, the easiest way to convert binary to Integer. You can also use the same strtoul function to convert hex values or octal values, rather any from any base you want. The better part is that function is availbe as part of the BSD libraries.

func hexToInt(binaryString: String) -> Int {
  return strtoul(binaryString, nil, 16)
}

hexToInt("F")      //       15
hexToInt("CD")     //      205
hexToInt("C0DE")   //    49374
hexToInt("F00D1E") // 15731998

Easy as that, if you have a pure Swift cool technique that helps you achieve the same, please let us know.

Views All Time
Views All Time
7665
Views Today
Views Today
1
Posted in Basics, Tip, Tutorial and tagged , , , , , , .