Ruby: how to save a file in UTF-16 Little Endian

I want to save ® to txt file with UTF-16 Little Endian, I tested in some way

1. The following is the encoding UTF-8

$RegisterMark=[174].pack('U*')
file = File.new("C:/Output.txt","w")
file.puts $RegisterMark
file.close

2. The following is the encoding UTF-16 Big Endian

require 'iconv'

$RegisterMark=[174].pack('U*')
$utf16RegisterMark =Iconv.conv('UTF-16', 'UTF-8', $RegisterMark )
file = File.new("C:/Output.txt","w")
file.puts $utf16RegisterMark 
file.close

The Iconv.conv mentor does not support the UTF-16 LE type.

How can I save output.txt with UTF16 LE?

+3
source share
2 answers

The easiest way is to simply open the file as UTF-16LE in the first place:

register_mark = "\00ua3" # or even just: register_mark = ®

File.open('C:/Output.txt', 'wt', encoding: 'UTF-16LE') do |f|
  f.puts register_mark
end

The important thing here is to explicitly indicate the encoding of the file using the key :encodingin the options Hashmethod File.new(or in this case File.open). Thus, the lines written to the file will be converted automatically, regardless of what encoding they are in.

Ruby:

  • Ruby snake_case, CamelCase .
  • , , .
  • Array#pack, , .
  • File.open, , .
  • t. (, , ), Windows, , , , .
+7

, . , ruby ​​ UTF-16LE w/BOM

## Adds BOM, albeit in a somewhat hacky way.
new_html_file = File.open(foo.txt, "w:UTF-8")
new_html_file << "\xFF\xFE".force_encoding('utf-16le') + some_text.force_encoding('utf-8').encode('utf-16le')
+2

All Articles