Convert Uint8List to String with Dart

后端 未结 4 1847

cipher.process returns an Uint8List which is a list of unsigned integers (0-255). I need to convert this Uint8List to a string that I can easily convert back to the same Uin

相关标签:
4条回答
  • 2021-01-07 19:02

    Dart uses UTF-16 to store Strings. For now in Dart there is no simple way of converting it easly to bytes and backwards. Therefore, you can use raw calculations to convert String to Uint8List and backwards.

    Dart code:

    import 'dart:typed_data';
    
    void main() {
      // Source
      String source = 'Hello! Cześć! 你好! ご挨拶!Привет! ℌ                                                                    
    0 讨论(0)
  • 2021-01-07 19:03

    I guess this should do it:

    String s = new String.fromCharCodes(inputAsUint8List);
    var outputAsUint8List = new Uint8List.fromList(s.codeUnits);
    
    0 讨论(0)
  • 2021-01-07 19:13

    To answer the specific question. I haven't used cipher.process, and can't find the docs. But if it just returns raw bytes, then perhaps these would be best encoded as hexidecimal or base64.

    Have a look at CryptoUtils.bytesToBase64, and CryptoUtils.bytesToHex.

    To answer the general question in the title, if the Uint8List contains UTF8 text, then use UTF8.decode() from the dart:convert library. See the api docs.

    import 'dart:convert';
    
    main() {
      var encoded = UTF8.encode("Îñţérñåţîöñåļîžåţîờñ");
      var decoded = UTF8.decode([0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6,
                               0x72, 0x67, 0x72, 0xc3, 0xb8, 0x64]);
    }
    

    String.fromCharCodes() takes a list of UTF-16 code units as input.

    Also see LATIN1 which will behave the same as String.fromCharCodes when the input is < 0xFF.

    0 讨论(0)
  • 2021-01-07 19:23
    Uint8List x;
    Utf8Decoder().convert(x);
    
    0 讨论(0)
提交回复
热议问题