使用Dart将Uint8List转换为String

时间:2015-02-17 15:41:27

标签: arrays string dart

cipher.process返回Uint8List,它是无符号整数列表(0-255)。我需要将这个Uint8List转换为一个我可以轻松转换回相同Uint8List的字符串。

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

ASCII.decode抛出错误,因为某些整数是> 127。

4 个答案:

答案 0 :(得分:12)

我想这应该这样做:

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

答案 1 :(得分:7)

回答具体问题。我没有使用过cipher.process,也找不到文档。但是如果它只是返回原始字节,那么也许这些最好编码为十六进制或base64。

查看CryptoUtils.bytesToBase64CryptoUtils.bytesToHex

要回答标题中的一般问题,如果Uint8List包含UTF8文本,则使用dart:convert库中的UTF8.decode()。请参阅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()将UTF-16代码单元列表作为输入。

另请参阅LATIN1,当输入为< {{3}}时,其行为与String.fromCharCodes相同。为0xFF。

答案 2 :(得分:0)

Dart使用UTF-16存储String。目前,在Dart中,没有简单的方法可以轻松地将其轻松转换为字节和向后。因此,您可以使用原始计算将String转换为Uint8List并向后转换。

Dart代码:

import 'dart:typed_data';

void main() {
  // Source
  String source = 'Hello! Cześć! 你好! ご挨拶!Привет! ℌ! !';
  print(source.length.toString() + ': "' + source + '" (' + source.runes.length.toString() + ')');

  // String (Dart uses UTF-16) to bytes
  var list = new List<int>();
  source.runes.forEach((rune) {
    if (rune >= 0x10000) {
      rune -= 0x10000;
      int firstWord = (rune >> 10) + 0xD800;
      list.add(firstWord >> 8);
      list.add(firstWord & 0xFF);
      int secondWord = (rune & 0x3FF) + 0xDC00;
      list.add(secondWord >> 8);
      list.add(secondWord & 0xFF);
    }
    else {
        list.add(rune >> 8);
        list.add(rune & 0xFF);
    }
  });
  Uint8List bytes = Uint8List.fromList(list);

  // Here you have `Uint8List` available

  // Bytes to UTF-16 string
  StringBuffer buffer = new StringBuffer();
  for (int i = 0; i < bytes.length;) {
    int firstWord = (bytes[i] << 8) + bytes[i + 1];
    if (0xD800 <= firstWord && firstWord <= 0xDBFF) {
      int secondWord = (bytes[i + 2] << 8) + bytes[i + 3];
      buffer.writeCharCode(((firstWord - 0xD800) << 10) + (secondWord - 0xDC00) + 0x10000);
      i += 4;
    }
    else {
        buffer.writeCharCode(firstWord);
      i += 2;
    }
  }

  // Outcome
  String outcome = buffer.toString();  
  print(outcome.length.toString() + ': "' + outcome + '" (' + outcome.runes.length.toString() + ')');
}

结果:

52: "Hello! Cześć! 你好! ご挨拶!Привет! ℌ! !" (43)
52: "Hello! Cześć! 你好! ご挨拶!Привет! ℌ! !" (43)

Run it online

答案 3 :(得分:0)

Uint8List x;
Utf8Decoder().convert(x);
相关问题