字符串转换为十六进制的红宝石 [英] Convert string to hexadecimal in Ruby

查看:124
本文介绍了字符串转换为十六进制的红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换成二进制文件使用Ruby为十六进制。

I'm trying to convert a Binary file to Hexadecimal using Ruby.

目前,我有以下几点:

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

这就是下面的code正在生成:

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

先谢谢了。

推荐答案

更改此行:

line = a.map { |b| ", #{b}" }.join

这样:

line = a.map { |b| sprintf(", 0x%02X",b) }.join

(必要时更改为%02X ,这是一个从例子中的十六进制数字是否应该大写不清楚。)

(Change to %02x if necessary, it's unclear from the example whether the hex digits should be capitalized.)

这篇关于字符串转换为十六进制的红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆