Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在ruby中将字符串转换为其二进制数值_Ruby_Byte - Fatal编程技术网

在ruby中将字符串转换为其二进制数值

在ruby中将字符串转换为其二进制数值,ruby,byte,Ruby,Byte,我对ruby非常陌生,目前正在尝试编写一个简单的ruby程序,从文件中读取1字节的块,并生成一个频率列表,列出每个块被看到的次数。然而,首先,我只是尝试索引一个256字节的数组,该数组对应于我读入的1个字节的每个可能字节值 问题似乎在于,to_i函数不根据二进制值转换字符,即“A”变为0,而不是ascii编码的65。ruby中还有其他内置的功能吗 freq = Array(0..255) File.open('temp.dat') do |file| until file.eof?

我对ruby非常陌生,目前正在尝试编写一个简单的ruby程序,从文件中读取1字节的块,并生成一个频率列表,列出每个块被看到的次数。然而,首先,我只是尝试索引一个256字节的数组,该数组对应于我读入的1个字节的每个可能字节值

问题似乎在于,to_i函数不根据二进制值转换字符,即“A”变为0,而不是ascii编码的65。ruby中还有其他内置的功能吗

freq = Array(0..255)

File.open('temp.dat') do |file|
  until file.eof?
    buf = file.read(1)
    puts "#{freq.at(buf.to_i)}"
  end
end
您正在寻找以下方法:


您可以执行以下任一操作:--

#                   ⇓⇓⇓
puts "#{freq.at(buf.ord)}"
1)  puts "#{freq.at(buf.ord)}"

2) puts "#{freq.at(buf.unpack('C')[0])}"