Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to hexadecimal in Ruby

Tags:

ruby

hex

binary

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", etc

Thanks in advance.

like image 499
fulvio Avatar asked Dec 02 '11 00:12

fulvio


4 Answers

Ruby 1.9 added an even easier way to do this: "0x101".hex will return the number given in hexadecimal in the string.

like image 104
Linuxios Avatar answered Sep 20 '22 14:09

Linuxios


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.)

like image 25
Peter O. Avatar answered Sep 18 '22 14:09

Peter O.


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" 
like image 24
Sean Hill Avatar answered Sep 20 '22 14:09

Sean Hill


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)
like image 26
jefflunt Avatar answered Sep 19 '22 14:09

jefflunt