Posts

Showing posts with the label bytesforbeginners

Bytes For Beginners: Cook Your Ain Conversions From Int Together With Double To Binary (And Other Pose Out Bases) Inwards Swift (Update: Xcode 8, Beta 6; Swift 3)

Why convert a decimal to a binary yourself when Swift tin create it for you? String(500, radix:2) Well it helps inwards learning: extension Int { func binary() -> String { var num = self var str = "" repeat { str = String(num%2) + str num = num/2 } piece num > 0 supply str } } 500.binary() And every bit you lot tin run into the procedure of going from base of operations 10 to base of operations two is a straightforward exercise. We just keep  dividing past times the base of operations give away in addition to adding the remainder  to the commencement of our string. In fact going from base of operations 10 to whatever base of operations from two through to ix is straightforward, because nosotros tin create just the same matter for those give away bases too. extension Int { func toBase(b:Int) -> String { guard b > 1 && b < xi else { fatalEr...