Skip to content

Instantly share code, notes, and snippets.

@sbellity
Created August 12, 2011 10:38
Show Gist options
  • Save sbellity/1141835 to your computer and use it in GitHub Desktop.
Save sbellity/1141835 to your computer and use it in GitHub Desktop.
BSON ObjectId conversion to base X
require 'rubygems'
require 'bson'
require 'string'
DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(//)
def dec2x(number, base=16)
number = Integer(number);
ret_hex = '';
hex_digit = DIGITS[0,base]
while(number != 0)
ret_hex = String(hex_digit[number % base] ) + ret_hex;
number = number / base;
end
return ret_hex; ## Returning HEX
end
oid = BSON::ObjectId.new
ii = oid.to_s.to_i(16)
puts "Original: #{oid.to_s}"
puts "Hex: #{dec2x(ii,16).to_s.downcase}"
puts "36 : #{dec2x(ii,36).to_s}"
puts "36 alt : #{ii.to_s(36)}"
puts "62 : #{dec2x(ii,62).to_s}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment