Bytes and binary data
suggest changeFiles, network sockets, images, audio, compressed archives and most wire protocols are sequences of bytes. Dart works with them through dart:typed_data, a core library that is available on every platform:
Uint8Listis the standard type for a sequence of bytes.File.readAsBytes(),utf8.encode(),base64.decode(), HTTP response bodies and sockets all give you aUint8List(or aList<int>that is one at runtime).- Other typed lists (
Int16List,Uint32List,Float64Listand so on) store fixed-size numbers packed next to each other, like a C array. ByteBufferis the raw memory behind a typed list. Several typed lists andByteDataobjects can share one buffer.ByteDatareads and writes integers and floating-point numbers of any size at any offset, in big-endian or little-endian byte order. This is the tool for parsing and producing binary formats.BytesBuildercollects bytes of unknown total length.
This article covers:
- creating and using
Uint8Listand the other typed lists - views that share memory versus copies
- reading and writing numbers with
ByteDataand byte order - building byte sequences with
BytesBuilder - a reusable reader and writer for your own binary format
- writing and parsing a WAV file, and detecting file types by magic bytes
- bit manipulation and varints
- binary files, streams and length-prefixed messages
- converting between bytes and text, and differences on the web
The examples were run with Dart 3.13.
Uint8List basics
A Uint8List has a fixed length and every element is an unsigned 8-bit value from 0 to 255:
import 'dart:typed_data';
void main() {
final a = Uint8List(4); // 4 zero bytes
a[0] = 0x48;
a[1] = 255;
a[2] = 256; // stored as 0
a[3] = -1; // stored as 255
print(a);
final b = Uint8List.fromList([1, 2, 3, 300]);
print(b);
print(a.length);
print(a.lengthInBytes);
print(a is List<int>);
try {
a.add(5);
} catch (e) {
print(e);
}
final c = Uint8ClampedList.fromList([-20, 100, 300]);
print(c);
}
[72, 255, 0, 255]
[1, 2, 3, 44]
4
4
true
Unsupported operation: Cannot add to a fixed-length list
[0, 100, 255]
Things to note:
Uint8List(n)createsnbytes set to zero.Uint8List.fromList()copies an existing list.- Values outside 0-255 are not rejected. Only the low 8 bits are stored, so 256 becomes 0, 300 becomes 44 and -1 becomes 255. This is convenient for bit manipulation but can hide bugs.
Uint8ListimplementsList<int>, so you can pass it anywhere aList<int>is expected and usefor,map,where,indexOf,sublistand the rest of the list API.- The length is fixed:
add,removeandlength =throw. UseBytesBuilder(below) when you don't know the size up front. Uint8ClampedListclamps out-of-range values to 0 or 255 instead of wrapping. It matches the pixel arrays of HTML canvas and is handy for image processing.
A plain List<int> uses 8 bytes or more per element; a Uint8List uses exactly one. When a function receives bytes as List<int>, it's usually a Uint8List already. If you need one and aren't sure, bytes is Uint8List ? bytes : Uint8List.fromList(bytes) avoids a needless copy.
Comparing byte lists
Typed lists don't override ==, so two lists with the same contents are not equal:
import 'dart:typed_data';
void main() {
final a = Uint8List.fromList([1, 2, 3]);
final b = Uint8List.fromList([1, 2, 3]);
print(a == b);
print(bytesEqual(a, b));
}
bool bytesEqual(List<int> a, List<int> b) {
if (identical(a, b)) return true;
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
false
true
package:collection has ListEquality().equals(a, b), which does the same. Don't use either for comparing secrets such as MAC tags or password hashes: they return early at the first difference, which leaks timing information. The Cryptography article shows constant-time comparison.
The other typed lists
dart:typed_data has a typed list for every common number format:
import 'dart:typed_data';
void main() {
final lists = <TypedData>[
Int8List(1),
Uint8List(1),
Int16List(1),
Uint16List(1),
Int32List(1),
Uint32List(1),
Int64List(1),
Uint64List(1),
Float32List(1),
Float64List(1),
];
for (final l in lists) {
print('${l.runtimeType.toString().padRight(12)} ${l.elementSizeInBytes} bytes');
}
final i16 = Int16List.fromList([32767, 32768, -32769]);
print(i16);
final f32 = Float32List.fromList([0.1, 1e40, 16777217]);
print(f32);
}
Int8List 1 bytes
Uint8List 1 bytes
Int16List 2 bytes
Uint16List 2 bytes
Int32List 4 bytes
Uint32List 4 bytes
Int64List 8 bytes
Uint64List 8 bytes
Float32List 4 bytes
Float64List 8 bytes
[32767, -32768, 32767]
[0.10000000149011612, Infinity, 16777216.0]
Integer lists wrap like Uint8List: 32768 doesn't fit in a signed 16-bit value and becomes -32768. Float32List stores single-precision floats, so values are rounded to about 7 significant digits, numbers that are too large become Infinity, and integers above 2^24 lose precision. Reading an element gives you back a normal Dart double.
Typed lists are much more compact and faster than List<int> or List<double> for large arrays of numbers. See Performance for a benchmark. They can also be sent cheaply between isolates and passed to native code with dart:ffi.
Views and buffers
Every typed list sits on top of a ByteBuffer. A view is a typed list (or ByteData) that uses all or part of an existing buffer instead of allocating its own memory. Changes through one view are visible through all the others:
import 'dart:typed_data';
void main() {
final bytes = Uint8List.fromList([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
final copy = bytes.sublist(2, 5); // new list, own memory
final view = Uint8List.sublistView(bytes, 2, 5); // shares memory
bytes[2] = 99;
print(copy);
print(view);
view[0] = 42; // writes through to bytes
print(bytes);
// A view of the same memory as 16-bit numbers.
final words = Uint16List.sublistView(bytes, 0, 4);
print(words);
print(Endian.host == Endian.little);
print(view.offsetInBytes);
print(view.buffer.lengthInBytes);
}
[2, 3, 4]
[99, 3, 4]
[0, 1, 42, 3, 4, 5, 6, 7, 8, 9]
[256, 810]
true
2
10
sublist()copies. Later changes to the original don't affect the copy.Uint8List.sublistView(list, start, end)creates a view. It's the fastest way to slice bytes, because nothing is copied. Every typed list type andByteDatahave asublistViewconstructor.Uint16List.sublistView(bytes, 0, 4)reads the first 4 bytes as two 16-bit numbers. Bytes[0, 1]became 256 because typed lists use the CPU's native byte order (Endian.host), which is little-endian on x64 and ARM. When the byte order of the data matters, useByteDatainstead.offsetInBytestells you where a view starts in its buffer, andbufferreturns the whole underlying buffer.
The buffer pitfall
The most common bug with views is calling .buffer on a list and assuming it contains only that list's bytes:
import 'dart:typed_data';
void main() {
final bytes = Uint8List.fromList([10, 20, 30, 40, 50, 60]);
final view = Uint8List.sublistView(bytes, 2);
// Wrong: asUint8List() on the buffer sees all 6 bytes.
print(view.buffer.asUint8List());
// Right: pass offset and length, or use sublistView.
print(view.buffer.asUint8List(view.offsetInBytes, view.lengthInBytes));
print(Uint8List.sublistView(view));
// Element offsets for wider views must be aligned.
try {
Uint32List.view(bytes.buffer, 1, 1);
} catch (e) {
print(e);
}
}
[10, 20, 30, 40, 50, 60]
[30, 40, 50, 60]
[30, 40, 50, 60]
RangeError: Offset (1) must be a multiple of BYTES_PER_ELEMENT (4)
view.buffer.asUint8List() returns the entire buffer, including bytes before and after the view. This bites people when they pass someBytes.buffer to an API, because a Uint8List you receive from a socket, utf8.encode() or a decoder may be a view into a larger buffer. Always pass offsetInBytes and lengthInBytes, or use sublistView, which takes care of it.
Views of multi-byte types created with the .view() constructors must start at an offset that is a multiple of the element size. ByteData has no alignment requirement, which is another reason to use it for parsing.
ByteData: numbers in a specific byte order
A 32-bit number takes 4 bytes. Big-endian order puts the most significant byte first (0x12345678 is stored as 12 34 56 78); little-endian puts it last (78 56 34 12). Network protocols, PNG, JPEG, Java class files and most crypto formats use big-endian. WAV, BMP, ZIP, and most formats designed on x86 PCs use little-endian.
ByteData has a getter and setter for every size: getUint8/setUint8, getInt16, getUint32, getInt64, getFloat32, getFloat64 and so on. Each takes a byte offset and an optional Endian, which defaults to Endian.big:
import 'dart:typed_data';
void main() {
final data = ByteData(16);
data.setUint16(0, 0xCAFE); // big-endian by default
data.setUint16(2, 0xCAFE, Endian.little);
data.setInt32(4, -2);
data.setFloat32(8, 1.5, Endian.little);
data.setUint32(12, 0xDEADBEEF);
final bytes = data.buffer.asUint8List();
print(bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' '));
print(data.getUint16(0).toRadixString(16));
print(data.getUint16(2).toRadixString(16)); // read with wrong order
print(data.getUint16(2, Endian.little).toRadixString(16));
print(data.getInt32(4));
print(data.getUint32(4));
print(data.getFloat32(8, Endian.little));
print(data.getUint8(12));
print(data.getInt8(12));
try {
data.getUint32(14);
} catch (e) {
print(e.runtimeType);
}
}
ca fe fe ca ff ff ff fe 00 00 c0 3f de ad be ef
cafe
feca
cafe
-2
4294967294
1.5
222
-34
IndexError
The same 4 bytes ff ff ff fe are -2 when read as signed and 4294967294 when read as unsigned. The bytes don't know their type; the format specification tells you which getter to use. Reading past the end throws an IndexError (a RangeError).
To read numbers from bytes you already have, wrap them in a view with ByteData.sublistView(). Nothing is copied, and it works correctly even if the bytes are a view into a larger buffer:
import 'dart:typed_data';
void main() {
final bytes = Uint8List.fromList([0xff, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x01]);
// Wrap existing bytes without copying.
final data = ByteData.sublistView(bytes, 1);
print(data.lengthInBytes);
print(data.getUint32(0));
print(data.getUint16(4));
// Uint8List.view on a ByteData buffer works the same way.
final back = Uint8List.sublistView(data);
print(back);
}
6
42
1
[0, 0, 0, 42, 0, 1]
Converting numbers to bytes and back
ByteData is also the easiest way to turn a single number into bytes, look at the bits of a floating-point number, or swap byte order:
import 'dart:typed_data';
Uint8List int32Bytes(int v, [Endian endian = Endian.big]) =>
Uint8List(4)..buffer.asByteData().setInt32(0, v, endian);
String hex(List<int> b) =>
b.map((x) => x.toRadixString(16).padLeft(2, '0')).join(' ');
void main() {
print(hex(int32Bytes(1)));
print(hex(int32Bytes(1, Endian.little)));
print(hex(int32Bytes(-1)));
// Reinterpret the bits of a double.
final d = ByteData(8)..setFloat64(0, 1.0);
print(hex(d.buffer.asUint8List()));
print(d.getUint64(0).toRadixString(16));
final f = Float32List.fromList([-0.0]);
print(Uint32List.view(f.buffer)[0].toRadixString(16));
// Swap the byte order of a 32-bit value.
final swap = ByteData(4)..setUint32(0, 0x11223344);
print(swap.getUint32(0, Endian.little).toRadixString(16));
}
00 00 00 01
01 00 00 00
ff ff ff ff
3f f0 00 00 00 00 00 00
3ff0000000000000
80000000
44332211
1.0 as an IEEE 754 double is 3ff0000000000000, and -0.0 as a float is just the sign bit. Writing a number in one byte order and reading it in the other swaps its bytes. For numbers larger than 64 bits, see Converting to and from bytes in the BigInt article.
Building bytes with BytesBuilder
When you produce output piece by piece and don't know the final size, use BytesBuilder:
import 'dart:convert';
import 'dart:typed_data';
void main() {
final builder = BytesBuilder(copy: false);
builder.addByte(0x01);
builder.add([0x02, 0x03]);
builder.add(utf8.encode('hi'));
final header = ByteData(4)..setUint32(0, 1000);
builder.add(header.buffer.asUint8List());
print(builder.length);
final bytes = builder.takeBytes(); // builder is now empty
print(bytes);
print(builder.length);
}
9
[1, 2, 3, 104, 105, 0, 0, 3, 232]
0
toBytes() returns a copy and keeps the contents, so you can call it again. takeBytes() returns the bytes and clears the builder, which avoids a copy when there was only one chunk.
BytesBuilder(copy: false) stores references to the lists you add instead of copying them. It's faster for big chunks, but only safe if you never modify those lists afterwards. Reusing a buffer breaks it:
import 'dart:typed_data';
void main() {
final scratch = ByteData(2);
final builder = BytesBuilder(copy: false);
for (final v in [1, 2, 3]) {
scratch.setUint16(0, v);
builder.add(scratch.buffer.asUint8List());
}
print(builder.toBytes()); // all three chunks are the same memory
}
[0, 3, 0, 3, 0, 3]
All three chunks point to the same 2 bytes, so the result contains the last value three times. Use the default BytesBuilder() (which copies) unless every chunk you add is a fresh list.
A reader and writer for binary formats
Parsing a binary format means keeping track of the current offset and reading fields one after another. Two small classes make this code read like the format specification. As an example, here is a custom file format that stores named points:
- 4 bytes: magic number
PTS1 - 2 bytes: number of points
- for each point: name as a 2-byte length followed by UTF-8 bytes, then x and y as 8-byte doubles
All numbers are big-endian.
import 'dart:convert';
import 'dart:typed_data';
class ByteWriter {
ByteWriter([this.endian = Endian.big]);
final Endian endian;
final _builder = BytesBuilder(); // copies; see the note below
final _scratch = ByteData(8);
int get length => _builder.length;
void uint8(int v) => _builder.addByte(v);
void uint16(int v) {
_scratch.setUint16(0, v, endian);
_builder.add(Uint8List.sublistView(_scratch, 0, 2));
}
void uint32(int v) {
_scratch.setUint32(0, v, endian);
_builder.add(Uint8List.sublistView(_scratch, 0, 4));
}
void float64(double v) {
_scratch.setFloat64(0, v, endian);
_builder.add(Uint8List.sublistView(_scratch, 0, 8));
}
void bytes(List<int> b) => _builder.add(b);
/// UTF-8 string prefixed with its byte length as uint16.
void string(String s) {
final b = utf8.encode(s);
uint16(b.length);
bytes(b);
}
Uint8List toBytes() => _builder.toBytes();
}
class ByteReader {
ByteReader(Uint8List bytes, [this.endian = Endian.big])
: _bytes = bytes,
_data = ByteData.sublistView(bytes);
final Uint8List _bytes;
final ByteData _data;
final Endian endian;
int offset = 0;
int get remaining => _bytes.length - offset;
void _need(int n) {
if (remaining < n) {
throw FormatException('Unexpected end of data', _bytes, offset);
}
}
int uint8() {
_need(1);
return _data.getUint8(offset++);
}
int uint16() {
_need(2);
final v = _data.getUint16(offset, endian);
offset += 2;
return v;
}
int uint32() {
_need(4);
final v = _data.getUint32(offset, endian);
offset += 4;
return v;
}
double float64() {
_need(8);
final v = _data.getFloat64(offset, endian);
offset += 8;
return v;
}
Uint8List bytes(int n) {
_need(n);
final v = Uint8List.sublistView(_bytes, offset, offset + n);
offset += n;
return v;
}
String string() => utf8.decode(bytes(uint16()));
}
class Point {
Point(this.name, this.x, this.y);
final String name;
final double x, y;
@override
String toString() => 'Point($name, $x, $y)';
}
const magic = 0x50545331; // "PTS1"
Uint8List encodePoints(List<Point> points) {
final w = ByteWriter()
..uint32(magic)
..uint16(points.length);
for (final p in points) {
w
..string(p.name)
..float64(p.x)
..float64(p.y);
}
return w.toBytes();
}
List<Point> decodePoints(Uint8List bytes) {
final r = ByteReader(bytes);
if (r.uint32() != magic) throw FormatException('Not a points file');
final count = r.uint16();
return [
for (var i = 0; i < count; i++) Point(r.string(), r.float64(), r.float64()),
];
}
void main() {
final bytes = encodePoints([Point('home', 52.23, 21.01), Point('Zürich', 47.37, 8.54)]);
print('${bytes.length} bytes');
print(bytes.take(16).map((b) => b.toRadixString(16).padLeft(2, '0')).join(' '));
print(decodePoints(bytes));
try {
decodePoints(Uint8List.sublistView(bytes, 0, 20));
} on FormatException catch (e) {
print('${e.message} at offset ${e.offset}');
}
}
53 bytes
50 54 53 31 00 02 00 04 68 6f 6d 65 40 4a 1d 70
[Point(home, 52.23, 21.01), Point(Zürich, 47.37, 8.54)]
Unexpected end of data at offset 20
Design notes:
- The writer uses one 8-byte
ByteDataas scratch space for each number, so it relies onBytesBuildercopying. This is exactly the bug from the previous section if you switch tocopy: false. - The reader checks the remaining length before each read and throws a
FormatExceptionwith the offset. Never trust lengths read from a file or network: a corrupted or malicious length can make you read garbage or allocate gigabytes. Check lengths against the remaining data and against a sensible maximum. bytes()returns a view, not a copy, so reading strings and blobs is cheap.- A magic number at the start lets you reject wrong files early. A version number right after it lets you change the format later.
For structured data that has to be exchanged between programs in different languages, a schema-based format is usually a better choice than a hand-written one; see Protocol Buffers.
Writing and reading a WAV file
WAV is a simple real-world format: a 44-byte little-endian header followed by raw samples. This example generates half a second of a 440 Hz tone, writes it to a file, and then reads back only the header and one sample with RandomAccessFile:
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
Uint8List makeWav(Int16List samples, {int sampleRate = 8000}) {
const channels = 1, bitsPerSample = 16;
final dataSize = samples.lengthInBytes;
final header = ByteData(44);
const le = Endian.little;
void ascii(int offset, String s) {
for (var i = 0; i < s.length; i++) {
header.setUint8(offset + i, s.codeUnitAt(i));
}
}
ascii(0, 'RIFF');
header.setUint32(4, 36 + dataSize, le);
ascii(8, 'WAVE');
ascii(12, 'fmt ');
header.setUint32(16, 16, le); // size of fmt chunk
header.setUint16(20, 1, le); // 1 = PCM
header.setUint16(22, channels, le);
header.setUint32(24, sampleRate, le);
header.setUint32(28, sampleRate * channels * bitsPerSample ~/ 8, le);
header.setUint16(32, channels * bitsPerSample ~/ 8, le);
header.setUint16(34, bitsPerSample, le);
ascii(36, 'data');
header.setUint32(40, dataSize, le);
// Int16List stores samples in host byte order, which is little-endian
// on all platforms Dart runs on today. Check it to be safe.
assert(Endian.host == Endian.little);
return (BytesBuilder(copy: false)
..add(header.buffer.asUint8List())
..add(samples.buffer.asUint8List(samples.offsetInBytes, dataSize)))
.takeBytes();
}
Future<void> main() async {
const sampleRate = 8000;
final samples = Int16List(sampleRate ~/ 2); // 0.5 s of a 440 Hz tone
for (var i = 0; i < samples.length; i++) {
samples[i] = (sin(2 * pi * 440 * i / sampleRate) * 12000).round();
}
final file = File('${Directory.systemTemp.path}/tone.wav');
await file.writeAsBytes(makeWav(samples, sampleRate: sampleRate));
print('wrote ${await file.length()} bytes');
// Read only the 44-byte header, not the whole file.
final raf = await file.open();
try {
final header = ByteData.sublistView(await raf.read(44));
String tag(int o) =>
String.fromCharCodes(Uint8List.sublistView(header, o, o + 4));
const le = Endian.little;
print('${tag(0)} ${tag(8)} ${tag(12)} ${tag(36)}');
print('channels: ${header.getUint16(22, le)}');
print('sample rate: ${header.getUint32(24, le)}');
print('bits: ${header.getUint16(34, le)}');
final dataSize = header.getUint32(40, le);
print('duration: ${dataSize / header.getUint32(28, le)} s');
// Jump to sample #2 and read it.
await raf.setPosition(44 + 2 * 2);
final s = ByteData.sublistView(await raf.read(2)).getInt16(0, le);
print('sample[2] = $s (expected ${samples[2]})');
} finally {
await raf.close();
}
await file.delete();
}
wrote 8044 bytes
RIFF WAVE fmt data
channels: 1
sample rate: 8000
bits: 16
duration: 0.5 s
sample[2] = 7649 (expected 7649)
The samples are stored in an Int16List, and its buffer is written directly to the file without converting each sample. That works because WAV is little-endian and so is Endian.host on every CPU Dart supports. If the format were big-endian, you would write each sample with ByteData.setInt16(..., Endian.big) instead.
RandomAccessFile lets you read a few bytes at any position without loading the whole file. That's how you read the header of a large media file or an index at the end of an archive. Remember to close it, ideally in a finally block.
Detecting file types by magic bytes
Most binary formats start with a fixed signature. Checking it is more reliable than trusting a file extension or a Content-Type header sent by a client:
import 'dart:typed_data';
String detectType(Uint8List b) {
bool startsWith(List<int> sig, [int at = 0]) {
if (b.length < at + sig.length) return false;
for (var i = 0; i < sig.length; i++) {
if (b[at + i] != sig[i]) return false;
}
return true;
}
if (startsWith([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) return 'png';
if (startsWith([0xFF, 0xD8, 0xFF])) return 'jpeg';
if (startsWith('GIF8'.codeUnits)) return 'gif';
if (startsWith('%PDF-'.codeUnits)) return 'pdf';
if (startsWith([0x50, 0x4B, 0x03, 0x04])) return 'zip';
if (startsWith([0x1F, 0x8B])) return 'gzip';
if (startsWith('RIFF'.codeUnits) && startsWith('WAVE'.codeUnits, 8)) return 'wav';
if (startsWith('RIFF'.codeUnits) && startsWith('WEBP'.codeUnits, 8)) return 'webp';
return 'unknown';
}
void main() {
final samples = {
'image.png': [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13],
'photo.jpg': [0xFF, 0xD8, 0xFF, 0xE0],
'doc.pdf': '%PDF-1.7\n'.codeUnits,
'tone.wav': [...'RIFF'.codeUnits, 0, 0, 0, 0, ...'WAVE'.codeUnits],
'notes.txt': 'hello'.codeUnits,
};
samples.forEach((name, bytes) {
print('$name: ${detectType(Uint8List.fromList(bytes))}');
});
}
image.png: png
photo.jpg: jpeg
doc.pdf: pdf
tone.wav: wav
notes.txt: unknown
You only need the first few bytes, so read them with file.openRead(0, 16) or RandomAccessFile.read(16). The mime package has a lookupMimeType('', headerBytes: bytes) function with a longer list of signatures. The File uploads article uses this to validate uploaded files.
Bit manipulation
Binary formats often pack several values into one byte or word. Dart has the usual bitwise operators: & (and), | (or), ^ (xor), ~ (not), << (shift left), >> (arithmetic shift right) and >>> (logical shift right):
void main() {
const value = 0xA5; // 1010 0101
print(value.toRadixString(2).padLeft(8, '0'));
// Test, set, clear and toggle bit 1 (counting from 0 on the right).
print((value >> 1) & 1);
print((value | (1 << 1)).toRadixString(2).padLeft(8, '0'));
print((value & ~(1 << 0)).toRadixString(2).padLeft(8, '0'));
print((value ^ 0xFF).toRadixString(2).padLeft(8, '0'));
// Split a byte into high and low nibbles.
print('${value >> 4} ${value & 0x0F}');
// Pack two 4-bit fields and a 24-bit field into one 32-bit word.
const version = 2, kind = 7, length = 1000000;
final word = (version << 28) | (kind << 24) | length;
print(word.toRadixString(16));
print('${word >>> 28} ${(word >> 24) & 0xF} ${word & 0xFFFFFF}');
// Dart ints are 64-bit, so ~ produces a negative number.
print(~0x0F);
print(~0x0F & 0xFF);
print((0xF0 << 4).toRadixString(16)); // no 8-bit overflow
print(((0xF0 << 4) & 0xFF).toRadixString(16));
print(-16 >> 2);
print(-16 >>> 60);
}
10100101
0
10100111
10100100
01011010
10 5
270f4240
2 7 1000000
-16
240
f00
0
-4
15
Dart's int is 64 bits, which matters when you translate code from C or Java:
~0x0Fis -16, not 240. Mask with& 0xFFto get an 8-bit result.- Shifting left doesn't overflow at 8, 16 or 32 bits.
0xF0 << 4is0xf00, not 0. Mask the result to the width you want. Storing into aUint8Listmasks automatically. >>keeps the sign of negative numbers;>>>shifts in zeros.toUnsigned(n)andtoSigned(n)convert to an n-bit value, for example0xFFFF.toSigned(16)is -1.
Variable-length integers
Many formats store integers in as few bytes as possible. The unsigned LEB128 varint used by Protocol Buffers and WebAssembly stores 7 bits per byte and uses the high bit to mean "more bytes follow":
import 'dart:typed_data';
/// Encodes a non-negative int as an unsigned LEB128 varint,
/// the format used by Protocol Buffers, WebAssembly and DWARF.
void writeVarint(BytesBuilder out, int value) {
if (value < 0) throw ArgumentError.value(value, 'value', 'must be >= 0');
while (value >= 0x80) {
out.addByte((value & 0x7F) | 0x80);
value >>= 7;
}
out.addByte(value);
}
/// Returns the decoded value and the number of bytes used.
(int, int) readVarint(Uint8List bytes, [int offset = 0]) {
var result = 0, shift = 0, i = offset;
while (true) {
if (i >= bytes.length) throw FormatException('Truncated varint');
final b = bytes[i++];
result |= (b & 0x7F) << shift;
if (b < 0x80) return (result, i - offset);
shift += 7;
if (shift > 63) throw FormatException('Varint too long');
}
}
void main() {
for (final n in [0, 1, 127, 128, 300, 1 << 40]) {
final out = BytesBuilder();
writeVarint(out, n);
final bytes = out.toBytes();
final (value, used) = readVarint(bytes);
final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' ');
print('${n.toString().padLeft(13)} -> $hex (decoded $value, $used bytes)');
}
}
0 -> 00 (decoded 0, 1 bytes)
1 -> 01 (decoded 1, 1 bytes)
127 -> 7f (decoded 127, 1 bytes)
128 -> 80 01 (decoded 128, 2 bytes)
300 -> ac 02 (decoded 300, 2 bytes)
1099511627776 -> 80 80 80 80 80 20 (decoded 1099511627776, 6 bytes)
readVarint returns a record with two values, which you take apart with a pattern. The length limit stops a stream of 0x80 bytes from looping forever.
Binary files and streams
dart:io has methods for reading and writing a whole file at once, and streams for processing large files in chunks:
import 'dart:io';
import 'dart:typed_data';
Future<void> main() async {
final file = File('${Directory.systemTemp.path}/bytes_demo.bin');
final data = Uint8List(200000);
for (var i = 0; i < data.length; i++) {
data[i] = i % 251;
}
await file.writeAsBytes(data);
// Whole file at once: fine for small files.
final all = await file.readAsBytes();
print('${all.runtimeType} ${all.length}');
// As a stream of chunks: constant memory for any file size.
var chunks = 0, total = 0, sum = 0;
await for (final chunk in file.openRead()) {
chunks++;
total += chunk.length;
for (final b in chunk) {
sum = (sum + b) & 0xFFFFFFFF;
}
}
print('$chunks chunks, $total bytes, sum $sum');
// Collect a stream into one Uint8List.
final builder = BytesBuilder(copy: false);
await file.openRead(1000, 1010).forEach(builder.add);
print(builder.takeBytes());
// Append bytes and write in pieces.
final sink = file.openWrite(mode: FileMode.append);
sink.add([1, 2, 3]);
sink.add(Uint8List(5));
await sink.close();
print(await file.length());
await file.delete();
}
Uint8List 200000
4 chunks, 200000 bytes, sum 24995206
[247, 248, 249, 250, 0, 1, 2, 3, 4, 5]
200008
readAsBytes()andwriteAsBytes()are the simplest choice for files that comfortably fit in memory. There are also synchronous versions,readAsBytesSync()andwriteAsBytesSync().openRead()returns aStream<List<int>>that delivers the file in chunks of up to 64 KB. Memory use stays constant no matter how large the file is. The optional start and end arguments read just a range.openWrite()returns anIOSink;add()takes anyList<int>. Alwaysawait sink.close()to flush the data.
Sockets, HTTP request and response bodies, and process output use the same Stream<List<int>> type, so the same code works for all of them. Transformers from dart:convert and dart:io plug into these streams: utf8.decoder turns bytes into text, gzip.decoder decompresses, and sha256 from package:crypto can hash a stream without loading it into memory.
Length-prefixed messages
A stream delivers bytes in whatever chunks the operating system produced. A chunk can contain half a message or three messages. To send separate messages over a TCP socket, a common approach is to prefix each message with its length and reassemble on the receiving side:
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
/// Prefixes a message with its length as a 4-byte big-endian number.
Uint8List frame(List<int> payload) {
final out = Uint8List(4 + payload.length);
ByteData.sublistView(out).setUint32(0, payload.length);
out.setRange(4, out.length, payload);
return out;
}
/// Turns a stream of arbitrary chunks back into whole messages.
Stream<Uint8List> unframe(Stream<List<int>> input) async* {
var buffer = Uint8List(0);
await for (final chunk in input) {
buffer = Uint8List.fromList([...buffer, ...chunk]);
while (buffer.length >= 4) {
final len = ByteData.sublistView(buffer).getUint32(0);
if (buffer.length < 4 + len) break; // wait for more data
yield Uint8List.sublistView(buffer, 4, 4 + len);
buffer = Uint8List.sublistView(buffer, 4 + len);
}
}
if (buffer.isNotEmpty) throw FormatException('${buffer.length} bytes left over');
}
Future<void> main() async {
final wire = BytesBuilder();
for (final msg in ['hello', 'binary', 'world 🌍']) {
wire.add(frame(utf8.encode(msg)));
}
final bytes = wire.toBytes();
print('${bytes.length} bytes on the wire');
// Simulate a socket that delivers data in 3-byte pieces.
Stream<List<int>> chunked() async* {
for (var i = 0; i < bytes.length; i += 3) {
yield bytes.sublist(i, i + 3 > bytes.length ? bytes.length : i + 3);
}
}
await for (final msg in unframe(chunked())) {
print(utf8.decode(msg));
}
}
33 bytes on the wire
hello
binary
world 🌍
unframe is an async generator that buffers incoming bytes until a whole message is available. For clarity it copies the buffer on every chunk; a production version would use a growing buffer or a list of chunks, and would reject lengths above a maximum message size. The same approach works with Socket, which is a Stream<Uint8List>.
Bytes and text
Text is bytes plus an encoding. Use the codec that matches how the bytes were produced:
import 'dart:convert';
import 'dart:typed_data';
void main() {
final bytes = Uint8List.fromList([0x63, 0x61, 0x66, 0xC3, 0xA9]); // "café" in UTF-8
print(utf8.decode(bytes));
print(latin1.decode(bytes)); // wrong encoding: mojibake
print(String.fromCharCodes(bytes)); // same as latin1
final invalid = Uint8List.fromList([0x61, 0xFF, 0x62]);
try {
utf8.decode(invalid);
} on FormatException catch (e) {
print(e.message);
}
print(utf8.decode(invalid, allowMalformed: true));
// Find a byte sequence inside a buffer.
final hay = utf8.encode('GET / HTTP/1.1\r\nHost: x\r\n\r\nbody');
print(hay.indexOf(0x0A));
print(indexOfBytes(hay, [13, 10, 13, 10]));
}
int indexOfBytes(List<int> hay, List<int> needle, [int start = 0]) {
outer:
for (var i = start; i <= hay.length - needle.length; i++) {
for (var j = 0; j < needle.length; j++) {
if (hay[i + j] != needle[j]) continue outer;
}
return i;
}
return -1;
}
café
café
café
Invalid UTF-8 byte
a�b
15
23
utf8.decode()is the right choice for almost all modern text. It throws aFormatExceptionon invalid input unless you passallowMalformed: true, which replaces bad bytes with U+FFFD.latin1.decode()andString.fromCharCodes()map each byte to one character. They never fail, so decoding UTF-8 with them silently produces garbage likecafé.indexOf()finds a single byte. For a byte sequence, such as the blank line that ends HTTP headers, write a small search loop.
More about encodings in Unicode and encodings. To show bytes as text, for logging or for storing them in JSON, use hex or Base64; see Base64 and hex encoding, which also has a hex dump function.
Bytes on the web
dart:typed_data works the same when compiled to JavaScript or WebAssembly, with one exception: JavaScript has no 64-bit integer arrays. With dart compile js, 64-bit types throw:
import 'dart:typed_data';
void main() {
final d = ByteData(8);
try {
d.setUint64(0, 1);
print('setUint64 ok');
} catch (e) {
print('setUint64: $e');
}
try {
Int64List(1);
print('Int64List ok');
} catch (e) {
print('Int64List: $e');
}
final u = Uint8List(1);
u[0] = 300;
print(u);
}
Native (VM and AOT):
setUint64 ok
Int64List ok
[44]
JavaScript:
setUint64: Unsupported operation: Uint64 accessor not supported by dart2js.
Int64List: Unsupported operation: Int64List not supported on the web.
[44]
If your code must run on the web, read 64-bit values as two 32-bit halves and combine them into a BigInt or keep them as two numbers. See BigInt on the web for why int itself is only exact up to 2^53 there. On the web, Uint8List is backed by a JavaScript Uint8Array, so bytes can be passed to browser APIs such as fetch and Blob without copying.
Tips
- Use
Uint8Listfor bytes, notList<int>. It's 8 times smaller and is what the platform libraries return. - Prefer views (
sublistView) over copies (sublist) when slicing, but copy when you keep a slice of a large buffer around for a long time; a small view keeps the whole buffer alive. - Never use
list.bufferwithoutoffsetInBytesandlengthInBytes. - Use
ByteDatawith an explicitEndianfor any data that is stored in a file or sent over a network. Use typed lists directly only for in-memory data or formats whose byte order matches the host. - Typed lists silently truncate out-of-range values. Validate numbers before you store them if a wrong value would corrupt your output.
- Validate every length and offset you read from untrusted data.
- Don't share a scratch buffer with
BytesBuilder(copy: false). ==on typed lists compares identity. Compare contents with a loop orListEquality.- For images use package:image, for compression
dart:io'sgzipandzlibcodecs orpackage:archive, and for hashing package:crypto, rather than parsing those formats yourself.