gotnull
gotnull

Reputation: 27214

Convert string to hexadecimal in Ruby

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.

Upvotes: 8

Views: 53011

Answers (5)

DGM
DGM

Reputation: 26979

For another approach, check out unpack

Upvotes: 5

Linuxios
Linuxios

Reputation: 35803

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

Upvotes: 26

Sean Hill
Sean Hill

Reputation: 15056

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" 

Upvotes: 8

Peter O.
Peter O.

Reputation: 32878

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

Upvotes: 10

jefflunt
jefflunt

Reputation: 33954

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)

Upvotes: 5

Related Questions