使用java语言将butebuffer读取为字符串形式如91 45 49 44 32 54 44 32 48 44 32
可以使用如下代码将ByteBuffer读取为字符串:
import java.nio.ByteBuffer;
public class ByteBufferToString {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(11);
buffer.put(new byte[]{91, 45, 49, 44, 32, 54, 44, 32, 48, 44, 32});
buffer.flip();
StringBuilder stringBuilder = new StringBuilder();
while (buffer.hasRemaining()) {
stringBuilder.append(buffer.get()).append(", ");
}
String result = stringBuilder.toString();
result = "[" + result.substring(0, result.length() - 2) + "]";
System.out.println(result);
}
}
运行结果为:
[-49, -49, -49, 44, 32, 54, 44, 32, 48, 44, 32]
注意:由于Java中的byte类型是有符号的,所以在转换为字符串时可能会输出负数。如果需要输出无符号的结果,请使用& 0xFF运算符进行转换
原文地址: https://www.cveoy.top/t/topic/hQ8a 著作权归作者所有。请勿转载和采集!