如何在Dart中获取字符串的字节?

gyo*_*o88 2 string byte encode dart flutter

如何读取DART中的字节String?在Java中,可以通过String方法实现getBytes()

看例子

Gün*_*uer 10

有一个codeUnitsgetter 返回UTF-16

String foo = 'Hello world';
List<int> bytes = foo.codeUnits;
print(bytes);
Run Code Online (Sandbox Code Playgroud)

[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

runes返回Unicode代码点

String foo = 'Hello world';
// Runes runes = foo.runes;
// or
Iterable<int> bytes = foo.runes;
print(bytes.toList());
Run Code Online (Sandbox Code Playgroud)

[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

  • 抱歉,我错了......你的是其他上下文的替代选择。谢谢 :) (3认同)

Mig*_*ivo 6

String foo = 'Hello world';
List<int> bytes = utf8.encode(foo);
print(bytes);
Run Code Online (Sandbox Code Playgroud)

输出:[72、101、108、108、111、32、119、111、114、108、100]

另外,如果您要转换回:

String bar = utf8.decode(bytes);
Run Code Online (Sandbox Code Playgroud)


Chu*_*son 5

如果您正在寻找 形式的字节Uint8List,请使用

import 'dart:convert';
import 'dart:typed_data';

var string = 'foo';
Uint8List.fromList(utf8.encode(string));
Run Code Online (Sandbox Code Playgroud)