How to get bytes of a String in Dart?
33,198
Solution 1
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);
Solution 2
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]
Solution 3
For images they might be base64 encoded, use
Image.memory(base64.decode('base64EncodedImageString')),
import function from
import 'dart:convert';
Author by
gyorgio88
Updated on February 18, 2022Comments
-
gyorgio88 over 2 years
How can I read the bytes of a
String
in dart? in Java it is possible through theString
methodgetBytes()
. -
Günter Zöchbauer over 5 yearsYup 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 ;-) -
gyorgio88 over 5 yearsI 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
-
Günter Zöchbauer over 5 years
utf8.encode()
returns individual bytes[229, 147, 148]
, my variants return[21716]
. Is this what you actually wanted because you accepted my answer? -
gyorgio88 over 5 yearssorry, i'm wrong ... yours is a alternative options for other contexts. thanks :)
-
JChen___ almost 3 yearsnice! but remember add import 'dart:convert';