Async and Practical
UTF-8 Decode
Bytes to String
utf8.decode from dart:convert reads a List<int> of byte values and returns the decoded String. For ASCII characters the byte count equals the character count; multi-byte UTF-8 sequences would change that ratio.
Program
Play the program to turn five ASCII bytes into the word Hello.
utf8_decode.dart
Replay: real traced execution (multi-file project)
import 'dart:convert';
void main() {
var bytes = [72, 101, 108, 108, 111];
var text = utf8.decode(bytes);
var size = bytes.length;
print('text="$text" bytes=$size');
}
bytes ← [72, 101, 108, 108, 111]
3void main() {4 var bytes = [72, 101, 108, 108, 111];5 var text = utf8.decode(bytes);values this step[72, 101, 108, 108, 111]bytestext ← Hello
4var bytes = [72, 101, 108, 108, 111];5var text = utf8.decode(bytes);6var size = bytes.length;values this stepHellotext[72, 101, 108, 108, 111]bytessize ← 5
5var text = utf8.decode(bytes);6var size = bytes.length;7print('text="$text" bytes=$size');values this step5size[72, 101, 108, 108, 111]bytesprint('text="$text" bytes=$size');
6 var size = bytes.length;7 print('text="$text" bytes=$size');8}outputtext="Hello" bytes=5values this stepHellotext5size
utf8 codec
`utf8` from `dart:convert` is the encoder/decoder for UTF-8 byte sequences.
utf8.decode
`utf8.decode(bytes)` turns a `List<int>` of byte values into a Dart `String`.
byte vs char
Each ASCII byte maps to one character, so `bytes.length == text.length` here; multi-byte UTF-8 would make these differ.