How to get UTF-16 byte array?

I have a UTF-8 string and I need to get a UTF-16 byte array, so how do I convert my string to a UTF-16 byte array?

Update:
I mean, we have the function Encoding.Unicode.GetBytes() or even Encoding.UTF8.GetBytes() to get a byte array of strings, but what about UTF-16 ? We do not have Encoding.UTF16.GetBytes() , so how can I get an array of bytes?

+6
source share
2 answers

For little-endian UTF-16, use Encoding.Unicode .

For big-endian UTF-16, use Encoding.BigEndianUnicode .

Alternatively, build an explicit UnicodeEncoding instance that allows you to specify the finiteness, enable or UnicodeEncoding byte bytes, and whether to exclude an exception from invalid data.

+10
source

I have a UTF-8 string and ...

No no. It's impossible. You may have a byte sequence (array or stream) that contains UTF-8 encoded text. But not string .

A.net string always contains Unicode (or, more precisely, UTF-16).

... so how can I convert my string to a UTF-16 byte array?

 string myText = ...; // some string, maybe from an UTF8 file or any other source byte[] utf16Data = Encoding.Unicode.GetBytes(mytext); 

The library defines the range of UTF7 , UTF8 , Unicode , UTF32 . Unicode is UTF16 in the context of the .NET platform.

+8
source

Source: https://habr.com/ru/post/953480/


All Articles