如何使用ruby将字节转换为base64

时间:2020-12-26 21:44:13

i want to convert bytes into the base64 format using ruby i tried this program but am not getting the proper output please help me

我想用ruby把字节转换成base64格式,我尝试了这个程序,但是没有得到正确的输出,请帮助我

require 'base64'
require 'open-uri'
str = File.new("/path/to/file.mp3")
a = Base64.encode64(str.each_byte{|byte| byte})
puts a

1 个解决方案

#1


3  

Use File.read and not File.new

使用文件。阅读并不是File.new

TO ENCODE WITHOUT CONVERTING TO BYTES USE:

require 'base64'
str = File.read("/path/to/file.mp3")
a = Base64.encode64(str)
puts a

EDIT to convert to bytes first before encoding use:

require 'base64'
str = File.read("/path/to/file.mp3")
a = Base64.encode64(str.each_byte.to_a.join)
puts a

#1


3  

Use File.read and not File.new

使用文件。阅读并不是File.new

TO ENCODE WITHOUT CONVERTING TO BYTES USE:

require 'base64'
str = File.read("/path/to/file.mp3")
a = Base64.encode64(str)
puts a

EDIT to convert to bytes first before encoding use:

require 'base64'
str = File.read("/path/to/file.mp3")
a = Base64.encode64(str.each_byte.to_a.join)
puts a