1

I am attempting to manipulate some system variables used by a program using Dart. I have encountered the problem of dart's utf package being discontinued, and I have not found any way to encode to UTF 16 Little Endian for a File.write. Is there a library that can do a byte to UTF 16 LE conversion in Dart? I would use UTF anyway, but it is not null safe. I may end up trying to use the utf package source code, but I am checking here to see if there is a native (or pub) implementation I have missed, as I am new to the world of UTF and byte conversions.

My goal:

encodeAsUtf16le(String s);

I do not need to write a BOM.

4

1 に答える 1

0

DartStringは内部的に UTF-16 を使用します。を使用String.codeUnitsして UTF-16 コード単位を取得し、リトルエンディアン形式で記述できます。

  var s = '\u{1F4A9}';
  var codeUnits = s.codeUnits;
  var byteData = ByteData(codeUnits.length * 2);
  for (var i = 0; i < codeUnits.length; i += 1) {
    byteData.setUint16(i * 2, codeUnits[i], Endian.little);
  }
  
  var bytes = byteData.buffer.asUint8List();
  await File('output').writeAsBytes(bytes);

または、リトル エンディアン システムで実行しているとします。

  var s = '\u{1F4A9}';
  var codeUnits = s.codeUnits;
  var bytes = Uint16List.fromList(codeUnits).buffer.asUint8List();
  await File('output').writeAsBytes(bytes);

https://stackoverflow.com/a/67802971/も参照してください。これは、UTF-16LE をStrings にエンコードすることに関するものです。

また、外部の要件によって強制されない限り、UTF-16 をディスクに書き込まないようにアドバイスしなければならないと感じています。

于 2021-06-22T20:02:59.433 に答える