Created
August 1, 2009 01:18
-
-
Save emiltin/159532 to your computer and use it in GitHub Desktop.
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
#is there an easy way to convert integers to radix 256? | |
#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