Skip to main content

Posts

Showing posts from April, 2016

Bytes for Beginners: Build your own Conversions from Int and Double to Binary (and Other Number Bases) in Swift (update: Xcode 8, beta 6; Swift 3)

Why convert a decimal to a binary yourself when Swift can do it for you? String(500, radix:2) Well it helps in learning: extension Int { func binary() -> String { var num = self var str = "" repeat { str = String(num%2) + str num = num/2 } while num > 0 return str } } 500.binary() And as you can see the process of going from base 10 to base 2 is a straightforward exercise. We simply keep  dividing by the base number and adding the remainder  to the beginning of our string. In fact going from base 10 to any base from 2 through to 9 is straightforward, because we can do exactly the same thing for those number bases too. extension Int { func toBase(b:Int) -> String { guard b > 1 && b < 11 else { fatalError("base too high") } var num = self var str = "" repeat { str = String(num