How can I read the bytes of a String
in dart?
in Java it is possible through the String
method getBytes()
.
Asked
Active
Viewed 5.6k times
4 Answers
82
import 'dart:convert';
String foo = 'Hello world';
List<int> bytes = utf8.encode(foo);
print(bytes);
Output: [72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
Also, if you want to convert back:
String bar = utf8.decode(bytes);

Miguel Ruivo
- 16,035
- 7
- 57
- 87
-
nice! but remember add import 'dart:convert'; – JChen___ Sep 23 '21 at 12:17
16
There is a codeUnits
getter that returns UTF-16
String foo = 'Hello world';
List<int> bytes = foo.codeUnits;
print(bytes);
[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
and runes
that returns Unicode code-points
String foo = 'Hello world';
// Runes runes = foo.runes;
// or
Iterable<int> bytes = foo.runes;
print(bytes.toList());
[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
Yup the differences will only show when you use multi-byte characters, but I don't know your use case and I don't know what `getBytes()` does exactly. I thought alternative options would at least be interesting to know ;-) – Günter Zöchbauer Feb 23 '19 at 18:03
-
I just tried utf8.encode() of the package 'dart:convert' and I get the desired result..E.G: print("哔".runes.length) return -> 1 byte, instead print(utf8.encode("哔").length) return -> 3 byte – gyorgio88 Feb 23 '19 at 18:10
-
1`utf8.encode()` returns individual bytes `[229, 147, 148]`, my variants return `[21716]`. Is this what you actually wanted because you accepted my answer? – Günter Zöchbauer Feb 23 '19 at 18:17
-
3sorry, i'm wrong ... yours is a alternative options for other contexts. thanks :) – gyorgio88 Feb 23 '19 at 18:21
5
If you're looking for bytes in the form of Uint8List
, use
import 'dart:convert';
import 'dart:typed_data';
var string = 'foo';
Uint8List.fromList(utf8.encode(string));

Chuck Batson
- 2,165
- 1
- 17
- 15
2
For images they might be base64 encoded, use
Image.memory(base64.decode('base64EncodedImageString')),
import function from
import 'dart:convert';

A.Mushate
- 395
- 3
- 7