在 Ruby 中将字符串转换为十六进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8350171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to hexadecimal in Ruby
提问by fulvio
I'm trying to convert a Binary file to Hexadecimal using Ruby.
我正在尝试使用 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
"116" => "0x74", 等等
Thanks in advance.
提前致谢。
回答by Linuxios
Ruby 1.9 added an even easier way to do this:
"0x101".hexwill return the number given in hexadecimal in the string.
Ruby 1.9 添加了一种更简单的方法来执行此操作:
"0x101".hex将返回字符串中以十六进制给出的数字。
回答by Peter O.
Change this line:
改变这一行:
line = a.map { |b| ", #{b}" }.join
to this:
对此:
line = a.map { |b| sprintf(", 0x%02X",b) }.join
(Change to %02xif necessary, it's unclear from the example whether the hex digits should be capitalized.)
(%02x如有必要,请更改为,示例中不清楚十六进制数字是否应大写。)
回答by Sean Hill
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"
回答by jefflunt
Binary to hex conversion in four languages(including Ruby) might be helpful.
四种语言(包括 Ruby)的二进制到十六进制转换可能会有所帮助。
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,但任何字符串表示都应该这样做。:
STDIN.read.to_i(base=16).to_s(base=2)

