//字符串转utf8
List
bytes = utf8.encode(foo);
print(bytes); //[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
//再将字节列表转字符串
String bar = utf8.decode(bytes);
//转utf16列表
bytes = foo.codeUnits;
print(bytes); //[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
//转unicode列表
print(foo.runes.toList()); //[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
//测试下中文以及表情的情况😊
foo="h😊好";
//字符串转utf8
bytes = utf8.encode(foo);
print(bytes); //[104, 240, 159, 152, 138, 229, 165, 189]
//转utf16列表
bytes = foo.codeUnits;
print(bytes); //[104, 55357, 56842, 22909]
//转unicode列表
print(foo.runes.toList()); //[104, 128522, 22909]
通过上面的例子可以发现:英文和数字的情况下转utf8 utf16 和unicode的结果都是一样的。
如果存在中文和表情符号,就会发现明显的差异。
utf8 : 英文占1位,中文占3位,表情占4位
utf16 : 英文占1位,中文占1位,表情占2位
unicode : 英文占1位,中文占1位,表情占1位