Skip to content

Instantly share code, notes, and snippets.

@emiltin
Created August 1, 2009 11:57
Show Gist options
  • Save emiltin/159645 to your computer and use it in GitHub Desktop.
Save emiltin/159645 to your computer and use it in GitHub Desktop.
#is there an easy way to convert integers to radix 256?
#to_s(radix) only accepts radi from 2 to 36.
#this methods works, but is there an easier way?
def base_256 n
s = ''
while n>0
s << (n % 256)
n >>= 8
end
s.reverse
end
n = 23423488694903409830495 #original number
s = base_256 n #convert to base 256 binary representation
m = s.unpack('B*')[0].to_i(2) #convert from string back to original number
#this almost works. the ideas is to first convert n to a string of hex nibbles using to_s(16).
#then take two hex nibbles at a time and convert to a single radix 256 byte.
#unfortunately it fails if to_s(16) returns a string with an odd number of bytes.
#it also seems longwinded...
s = n.to_s(16).scan(/../).inject('') { |out,hex| out << hex.to_i(16) }
m = s.unpack('B*')[0].to_i(2) #convert from string back to original number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment