Created
June 2, 2015 16:06
-
-
Save regnerjr/699f8f9ca363b9a70dd9 to your computer and use it in GitHub Desktop.
A couple functions for doing Integer to Binary Conversion in swift.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| func intToBin(num: Int, padding: Bool = true ) -> String { | |
| var binString = String(num, radix:2) | |
| if padding { | |
| binString = padStringTo4DigitChunks(binString) | |
| } | |
| return binString | |
| } | |
| func padStringTo4DigitChunks(binString:String) -> String { | |
| //hexStringWill alwasy be "1001" easily stored as ascii | |
| let numToPad = binString.lengthOfBytesUsingEncoding(NSASCIIStringEncoding) % 4 | |
| switch numToPad { | |
| case 1: return "000" + binString | |
| case 2: return "00" + binString | |
| case 3: return "0" + binString | |
| default: return binString //default to no padding | |
| } | |
| } | |
| intToBin(1, padding: true) // "0001" | |
| intToBin(1) // "1" | |
| intToBin(5, padding: true) // "0101" | |
| intToBin(8, padding: true) // 1000 | |
| intToBin(15, padding: true) // 1111 | |
| intToBin(16) // 1_0000 | |
| intToBin(16, padding: true) //since 16 has 5 binary digits 0001_0000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment