Convert string to hexadecimal in Ruby
Solution 1
Change this line:
line = a.map { |b| ", #{b}" }.join
to this:
line = a.map { |b| sprintf(", 0x%02X",b) }.join
(Change to %02x
if necessary, it's unclear from the example whether the hex digits should be capitalized.)
Solution 2
Ruby 1.9 added an even easier way to do this:
"0x101".hex
will return the number given in hexadecimal in the string.
Solution 3
I don't know if this is the best solution, but this a solution:
class String
def to_hex
"0x" + self.to_i.to_s(16)
end
end
"116".to_hex
=> "0x74"
Solution 4
Binary to hex conversion in four languages (including Ruby) might be helpful.
One of the comments on that page seems to provide a very easy short cut. The example covers reading input from STDIN
, but any string representation should do.:
STDIN.read.to_i(base=16).to_s(base=2)
Solution 5
For another approach, check out unpack
fulvio
Updated on August 02, 2022Comments
-
fulvio almost 2 years
I'm trying to convert a Binary file to Hexadecimal using Ruby.
At the moment I have the following:
File.open(out_name, 'w') do |f| f.puts "const unsigned int modFileSize = #{data.length};" f.puts "const char modFile[] = {" first_line = true data.bytes.each_slice(15) do |a| line = a.map { |b| ",#{b}" }.join if first_line f.puts line[1..-1] else f.puts line end first_line = false end f.puts "};" end
This is what the following code is generating:
const unsigned int modFileSize = 82946; const char modFile[] = { 116, 114, 97, 98, 97, 108, 97, 115, 104, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 62, 62, 62, 110, 117, 107, 101, 32, 111, 102 , 32, 97, 110, 97, 114, 99, 104, 121, 60, 60, 60, 8, 8, 130, 0 };
What I need is the following:
const unsigned int modFileSize = 82946; const char modFile[] = { 0x74, 0x72, etc, etc };
So I need to be able to convert a string to its hexadecimal value.
"116" => "0x74"
, etcThanks in advance.
-
Cary Swoveland over 8 yearsYou don't need
.self
, though I realize some like to have it anyway. -
Jason Axelson over 7 yearsThat link is now dead
-
DGM over 7 yearsThanks, I changed it to standard documentation. A simple google search for "ruby unpack" will find several other descriptions.
-
noraj over 4 yearsThis does exactly the opposite
'0xff'.hex => 255
this convert an hex to decimal. -
Linuxios over 4 years@noraj: The sentence was very unclear, you're right — I've edited it.