问题
How can I read the bytes of a String
in dart?
in Java it is possible through the String
method getBytes()
.
See example
回答1:
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);
回答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]
来源:https://stackoverflow.com/questions/54844119/how-to-get-bytes-of-a-string-in-dart