2021-09-28

flutter中字符串如何转为字节数组bytes?

flutter中字符串如何转为字节数组bytes?

链接: http://www.findsrc.com/article/flutter_string_to_bytes

String foo = 'Hello world';
//字符串转utf8
List<int> 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位

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值