Convert Uint8List to String with Dart

2019-06-19 01:28发布

问题:

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 Uint8List.

    var cipherText = cipher.process( inputAsUint8List );        
    return ASCII.decode(cipherText);

ASCII.decode throws an error since some of the integers are > 127.

回答1:

I guess this should do it:

String s = new String.fromCharCodes(inputAsUint8List);
var outputAsUint8List = new Uint8List.fromList(s.codeUnits);


回答2:

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.



回答3:

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ść! 你好! ご挨拶!Привет! ℌ