Created
August 19, 2023 19:37
-
-
Save Beyarz/4c4c3191c57fa932ea37178bd7d9303a to your computer and use it in GitHub Desktop.
Convert integer to binary
This file contains 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
def itob(number) | |
decimals = [] | |
while (number.positive?) | |
number, remainder = number.divmod(2) | |
decimals << remainder | |
end | |
bits = decimals.length.times.map { |i| 2**i } | |
validate_sum = 0 | |
decimals.each_with_index { |el, i| validate_sum += bits[i] if el.positive? } | |
"Bits: #{decimals.length}, Binary: #{decimals.join}, Number: #{validate_sum}" | |
end | |
puts itob(323) | |
#=> Bits: 9, Binary: 110000101, Number: 323 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment