I have an array of UCS-2LE encoded bytes in Ruby and since this is my complete beginning with Ruby I'm struggling to convert it to UTF-8 string, I have the same code in PHP & Java working just fine.
In PHP I'm using iconv library, but in Ruby iconv has been deprecated:
$str = iconv('UCS-2LE', 'UTF-8//IGNORE', implode($byte_array));
In Java I'm using:
str = new String(byte_array, "UTF-16LE");
Bytes in the array are encoded as 2 bytes per 1 character, how to perform similar conversion in Ruby? I've tried a few solutions but it didn't work for me. Thank you.
byte_array.pack("C*").force_encoding("UTF-16LE").encode("UTF-8")should workCinterprets an integer value as a 1-byte char, i.e.[65].pack("C")converts65(0x41) to"A"("\x41"). The result is a string with ASCII-8BIT encoding.force_encodingthen reinterprets the bytes.