cipher.prrocess返回一个Uint8List,它是一个无符号整数(0-255)的列表。我需要将这个Uint8List转换为一个字符串,我可以很容易地将其转换回相同的Uint8List。
var cipherText = cipher.process( inputAsUint8List );
return ASCII.decode(cipherText);
ASCII.decode抛出一个错误,因为有些整数大于127。
我想应该这样做:
String s = new String.fromCharCodes(inputAsUint8List);
var outputAsUint8List = new Uint8List.fromList(s.codeUnits);
回答特定问题。我没有使用cipher.prrocess,也找不到文档。但如果它只返回原始字节,那么这些字节最好编码为十六进制或base64。
看看CryptoUtils.bytesToBase64和CryptoUtils.bytesToHex.
要回答标题中的一般问题,如果Uint8List包含UTF8文本,则使用dart:convert库中的UTF8.decode()。请参阅api文档。
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,当输入<0xFF。
Uint8List x;
Utf8Decoder().convert(x);
Dart使用UTF-16来存储String
s。目前,在Dart中,没有简单的方法可以将其转换为字节并向后转换。因此,可以使用原始计算将String
转换为Uint8List
并向后转换。
飞镖代码:
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)
在线运行
试试这个代码:
String uint8ListToHexString(Uint8List uint8list) {
var hex = "";
for (var i in uint8list) {
var x = i.toRadixString(16);
if(x.length == 1){
x = "0$x";
}
hex += x;
}
return hex;
}