gpt4 book ai didi

flutter - 如何使用ByteArrayOutputStream和ByteBuffer

转载 作者:行者123 更新时间:2023-12-03 03:55:50 28 4
gpt4 key购买 nike

我有Java代码,如何用dart编写代码?

我需要将一些String写入套接字,但是在此之前,我需要写入此字符串的长度。因此,我使用ByteBuffer类创建具有字符串长度的某些字节数组,然后将这两个字节数组连接起来。谢谢。

public void writeUTF(String s, OutputStream out) throws IOException {
if (s != null) {

ByteArrayOutputStream bytArray = new ByteArrayOutputStream();

int length = s.getBytes("UTF-8").length;

// Create buffer
byte[] bytesMessageLenght = ByteBuffer.allocate(4).putInt(length).array();
byte[] bytes = s.getBytes();

bytArray.write(bytesMessageLenght);
bytArray.write(bytes);

// Write
out.write(bytArray.toByteArray());
out.flush();
}
}

最佳答案

使用Dart ByteData可以直接设置长度,然后使用asUint8List制作要复制的字节数组。

Uint8List encode(String s) {
var encodedString = utf8.encode(s);
var encodedLength = encodedString.length;
var data = ByteData(encodedLength + 4);
data.setUint32(0, encodedLength, Endian.big);
var bytes = data.buffer.asUint8List();
bytes.setRange(4, encodedLength + 4, encodedString);
return bytes;
}

关于flutter - 如何使用ByteArrayOutputStream和ByteBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61335554/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com