Last active
May 26, 2021 12:01
-
-
Save andrew-wilkes/63804dc15c46c954f0f993aad432749f to your computer and use it in GitHub Desktop.
Convert an Integer to a Binary String
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
| var num_bits_index = 0 | |
| var bit_lengths = [4, 8, 16] | |
| func int2binary(x: int) -> String: | |
| var b = "" | |
| for n in bit_lengths[num_bits_index]: | |
| b = String(x % 2) + b | |
| x /= 2 | |
| return b |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To ensure that the index does not go out of bounds you may enter:
for n in bit_lengths[num_bits_index % bit_lengths.size()]: