【问题标题】:How to Decoding and encoding UTF-8 characters in flutter如何在 Flutter 中解码和编码 UTF-8 字符
【发布时间】:2022-01-13 23:02:15
【问题描述】:

如何使用 UTF-8 编码和解码相同的字符串。我正在尝试解码 UTF-8 格式的字符串

我有以下 UTF-8 字符串:-

List<int> utf8Bytes = [
  0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9,
  0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3,
  0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4,
  0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5,
  0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1
];

有什么方法可以在 Dart 中解码这个 UTF-8 字符串?任何帮助将不胜感激。

【问题讨论】:

    标签: dart encoding utf-8 decoding converters


    【解决方案1】:

    使用 utf8.decode() 将 UTF8 编码的字节解码为 Dart 字符串:

    List<int> utf8Bytes = [
      0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9,
      0x72, 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3,
      0xae, 0xc3, 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4,
      0xbc, 0xc3, 0xae, 0xc5, 0xbe, 0xc3, 0xa5, 0xc5,
      0xa3, 0xc3, 0xae, 0xe1, 0xbb, 0x9d, 0xc3, 0xb1
    ];
    
    var funnyWord = utf8.decode(utf8Bytes);
    
    assert(funnyWord == 'Îñţérñåţîöñåļîžåţîờñ');
    

    要将 UTF-8 字符流转换为 Dart 字符串,请将 utf8.decoder 指定为 Stream transform() 方法:

    var lines = utf8.decoder
        .bind(inputStream)
        .transform(const LineSplitter());
    try {
      await for (final line in lines) {
        print('Got ${line.length} characters from stream');
      }
      print('file is now closed');
    } catch (e) {
      print(e);
    }
    

    使用utf8.encode() 将 Dart 字符串编码为 UTF8 编码字节列表:

    List<int> encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');
    
    assert(encoded.length == utf8Bytes.length);
    for (int i = 0; i < encoded.length; i++) {
      assert(encoded[i] == utf8Bytes[i]);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-24
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 2011-06-17
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      相关资源
      最近更新 更多