Skip to content

Instantly share code, notes, and snippets.

@xadn
Created February 27, 2011 21:03
Show Gist options
  • Save xadn/846537 to your computer and use it in GitHub Desktop.
Save xadn/846537 to your computer and use it in GitHub Desktop.
Ruby zero pad a number and convert it to binary
# add leading zeros to a number
def zero_pad(target_length, input_string)
pad_length = target_length - input_string.length
"0" * pad_length + input
end
# convert a number to binary
address.to_i.to_s(2)
#to_i converts the string to an integer
#to_s(2) converts the integer in base 2 to a string
@karatedog
Copy link

There are built-in solution for this:

1.9.2-p320 :002 > sprintf("%b", 2435)
 => "100110000011" 

1.9.2-p320 :001 > sprintf("%.15b", 2435)
 => "000100110000011" 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment