I have the following minimal ruby script to test base64 encoding
require "base64"
data = "testkjadlskjflkasjfwe08u185u12w3oqew,dmf.smxa"
path = "./example/ruby_data.bin"
encoded = Base64.encode64 data
puts encoded
open(path, "wb") do |file|
file << encoded
end
However, I have the issue when I read the file in for instance C , Ruby, or Python there is a newline at the end of the string. I would like to avoid that. How can I do this?
CodePudding user response:
The line feed is generated as part of the encoding process of Base64.encode64
.
encode64(bin)
Returns the Base64-encoded version of
bin
. This method complies with RFC 2045. Line feeds are added to every 60 encoded characters.
require 'base64' Base64.encode64("Now is the time for all good coders\nto learn Ruby")
Generates:
Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g UnVieQ==
There is also Base64.strict_encode64
which doesn't add any line feeds.
strict_encode64(bin)
Returns the Base64-encoded version of
bin
. This method complies with RFC 4648. No line feeds are added.
data = "testkjadlskjflkasjfwe08u185u12w3oqew,dmf.smxa"
Base64.encode64 data
#=> "dGVzdGtqYWRsc2tqZmxrYXNqZndlMDh1MTg1dTEydzNvcWV3LGRtZi5zbXhh\n"
Base64.strict_encode64 data
#=> "dGVzdGtqYWRsc2tqZmxrYXNqZndlMDh1MTg1dTEydzNvcWV3LGRtZi5zbXhh"
With the line feed(s) removed from the encoded string it is also not written to the file.