在 Ruby 中将字符串转换为十六进制
我正在尝试使用 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”等
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Ruby 1.9 添加了一种更简单的方法来做到这一点:
"0x101".hex
将返回字符串中以十六进制给出的数字。Ruby 1.9 added an even easier way to do this:
"0x101".hex
will return the number given in hexadecimal in the string.将此行:更改
为:(
如有必要,请更改为
%02x
,从示例中不清楚十六进制数字是否应大写。)Change this line:
to this:
(Change to
%02x
if necessary, it's unclear from the example whether the hex digits should be capitalized.)我不知道这是否是最好的解决方案,但这是一个解决方案:
I don't know if this is the best solution, but this a solution:
二进制到十六进制转换四语言(包括 Ruby)可能会有所帮助。
该页面上的一条评论似乎提供了一条非常简单的捷径。该示例涵盖从
STDIN
读取输入,但任何字符串表示形式都可以。: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.:对于另一种方法,请查看 unpack
For another approach, check out unpack