Integer to binary and Hex


Integer to binary:


def bin(n)
  m = '' 
  while(n>0) do 
    m = (n%2).to_s + m
    n = n/2
  end
  m
end

Integer to Hex:


def hex(n)
  m=''
  hex_map={'10' => 'A', '11' => 'B', '12' => 'C', '13' => 'D', '14' => 'E', '15' => 'F' }
  while(n>0) do
    r = (n%16) 
    r = hex_map[r.to_s] if r > 9
    m = r.to_s + m
    n = n/16
  end
  m
end
Advertisements

I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: ,
Posted in Algorithm, Interview questions, Ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

StackOverFlow
Categories
Archives
%d bloggers like this: