Skip to content

Instantly share code, notes, and snippets.

@Beyarz
Created August 19, 2023 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Beyarz/4c4c3191c57fa932ea37178bd7d9303a to your computer and use it in GitHub Desktop.
Save Beyarz/4c4c3191c57fa932ea37178bd7d9303a to your computer and use it in GitHub Desktop.
Convert integer to binary
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