我正在尝试使用 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
这是以下代码生成的内容:
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
};
我需要的是:
const unsigned int modFileSize = 82946;
const char modFile[] = {
0x74, 0x72, etc, etc
};
所以我需要能够将字符串转换为其十六进制值。
"116"=> "0x74"
等
提前致谢。
最佳答案
Ruby 1.9 添加了一种更简单的方法来做到这一点:
"0x101".hex
将返回字符串中以十六进制形式给出的数字。
关于ruby - 在 Ruby 中将字符串转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8350171/