[ruby] Converting an integer to a hexadecimal string in Ruby

Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?

Something like the opposite of String#to_i:

"0A".to_i(16) #=>10

Like perhaps:

"0A".hex #=>10

I know how to roll my own, but it's probably more efficient to use a built in Ruby function.

This question is related to ruby hex base-conversion

The answer is

You can give to_s a base other than 10:

10.to_s(16)  #=> "a"

Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum#to_s and BigNum#to_s

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

To summarize:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

Here's another approach:

sprintf("%02x", 10).upcase

see the documentation for sprintf here: http://www.ruby-doc.org/core/classes/Kernel.html#method-i-sprintf

Just in case you have a preference for how negative numbers are formatted:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"

Questions with ruby tag:

Uninitialized Constant MessagesController Embed ruby within URL : Middleman Blog Titlecase all entries into a form_for text field Ruby - ignore "exit" in code Empty brackets '[]' appearing when using .where find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException) How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite? How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? How to update Ruby with Homebrew? Ruby: How to convert a string to boolean Can't install gems on OS X "El Capitan" How to resolve "gpg: command not found" error during RVM installation? How to install Ruby 2.1.4 on Ubuntu 14.04 The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256 Cannot install Aptana Studio 3.6 on Windows AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint How to avoid "cannot load such file -- utils/popen" from homebrew on OSX RVM is not a function, selecting rubies with 'rvm use ...' will not work How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1) Check if not nil and not empty in Rails shortcut? ActionController::UnknownFormat Failed to build gem native extension (installing Compass) Rails formatting date converting epoch time with milliseconds to datetime TypeError: no implicit conversion of Symbol into Integer RSpec: how to test if a method was called? Execute a command line binary with Node.js Error while installing json gem 'mkmf.rb can't find header files for ruby' How to downgrade or install an older version of Cocoapods How to select option in drop down using Capybara PG::ConnectionBad - could not connect to server: Connection refused Append key/value pair to hash with << in Ruby How to delete specific characters from a string in Ruby? Create Directory if it doesn't exist with Ruby SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/ Rails 4 LIKE query - ActiveRecord adds quotes How to find where gem files are installed Installing RubyGems in Windows Rails 4: assets not loading in production Which Ruby version am I really running? Installing Bootstrap 3 on Rails App Rails 4: List of available datatypes Why do I get a "permission denied" error while installing a gem? How to install a specific version of a ruby gem? Rails 4: before_filter vs. before_action Rails 4 Authenticity Token Testing for empty or nil-value string Ruby class instance variable vs. class variable Determining type of an object in ruby

Questions with hex tag:

Transparent ARGB hex value How to convert a hex string to hex number Javascript: Unicode string to hex Converting Hexadecimal String to Decimal Integer Convert string to hex-string in C# Print a variable in hexadecimal in Python Convert ascii char[] to hexadecimal char[] in C Hex transparency in colors printf() formatting for hex Python Hexadecimal PHP convert string to hex and hex to string How to convert hex string to Java string? Decimal to Hexadecimal Converter in Java Hexadecimal To Decimal in Shell Script Conversion hex string into ascii in bash command line Print a string as hex bytes? Java converting int to hex and back again String.Format for Hex Convert hex string to int bitwise XOR of hex numbers in python C++: Converting Hexadecimal to Decimal Char array to hex string C++ How to convert a byte array to a hex string in Java? Convert from ASCII string encoded in Hex to plain ASCII? Java Convert integer to hex integer Convert hexadecimal string (hex) to a binary string How do I convert hex to decimal in Python? Convert bytes to bits in python How to convert hex strings to byte values in Java What do numbers using 0x notation mean? How do I convert a single character into it's hex ascii value in python Printing hexadecimal characters in C What's the correct way to convert bytes to a hex string in Python 3? How to convert a color integer to a hex String in Android? Write bytes to file How do you convert a byte array to a hexadecimal string in C? How to get the background color code of an element in hex? Hexadecimal to Integer in Java Python convert decimal to hex Ascii/Hex convert in bash RGB to hex and hex to RGB Generating a random hex color code with PHP Programmatically Lighten or Darken a hex color (or rgb, and blend colors) Need a good hex editor for Linux Understanding colors on Android (six characters) How to get a Color from hexadecimal Color String Integer to hex string in C++ Convert a String of Hex into ASCII in Java How to display hexadecimal numbers in C? Create a hexadecimal colour based on a string with JavaScript

Questions with base-conversion tag:

Converting binary to decimal integer output Converting an integer to a hexadecimal string in Ruby