如何原生转换字符串 - > base64和base64 - > 字符串
我发现只有这个字节到base64string
我想这样:
String Base64String.encode();
String Base64String.decode();
Run Code Online (Sandbox Code Playgroud)
或者从另一种语言移植更容易?
您可以使用转换库中的BASE64编解码器(base64在Dart 2中重命名)和LATIN1编解码器(latin1在Dart 2中重命名).
var stringToEncode = 'Dart is awesome';
// encoding
var bytesInLatin1 = LATIN1.encode(stringToEncode);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]
var base64encoded = BASE64.encode(bytesInLatin1);
// RGFydCBpcyBhd2Vzb21l
// decoding
var bytesInLatin1_decoded = BASE64.decode(base64encoded);
// [68, 97, 114, 116, 32, 105, 115, 32, 97, 119, 101, 115, 111, 109, 101]
var initialValue = LATIN1.decode(bytesInLatin1_decoded);
// Dart is awesome
Run Code Online (Sandbox Code Playgroud)
如果您始终用于LATIN1生成编码的String,则可以通过创建编解码器来直接将String转换为编码的String或从编码的String转换来避免2次转换调用.
var codec = LATIN1.fuse(BASE64);
print(codec.encode('Dart is awesome'));
// RGFydCBpcyBhd2Vzb21l
print(codec.decode('RGFydCBpcyBhd2Vzb21l'));
// Dart is awesome
Run Code Online (Sandbox Code Playgroud)
截至 0.9.2 的crypto包
CryptoUtils已弃用。请改用包中的Base64APIdart:convert和十六进制 APIconvert。
import 'dart:convert' show utf8, base64;
main() {
final str = 'https://dartpad.dartlang.org/';
final encoded = base64.encode(UTF8.encode(str));
print('base64: $encoded');
final str2 = utf8.decode(base64.decode(encoded));
print(str2);
print(str == str2);
}
Run Code Online (Sandbox Code Playgroud)
在DartPad 中尝试
我会评论Günter2016年4月10日的帖子,但我没有声誉.正如他所说,你dart:convert现在应该使用这个库.你必须结合几个编解码器来从base64字符串中获取utf8字符串,反之亦然.本文说,融合您的编解码器更快.
import 'dart:convert';
void main() {
var base64 = 'QXdlc29tZSE=';
var utf8 = 'Awesome!';
// Combining the codecs
print(utf8 == UTF8.decode(BASE64.decode(base64)));
print(base64 == BASE64.encode(UTF8.encode(utf8)));
// Output:
// true
// true
// Fusing is faster, and you don't have to worry about reversing your codecs
print(utf8 == UTF8.fuse(BASE64).decode(base64));
print(base64 == UTF8.fuse(BASE64).encode(utf8));
// Output:
// true
// true
}
Run Code Online (Sandbox Code Playgroud)
https://dartpad.dartlang.org/5c0e1cfb6d1d640cdc902fe57a2a687d
| 归档时间: |
|
| 查看次数: |
5704 次 |
| 最近记录: |