简体   繁体   English

将 CharBuffer 转换为 ByteBuffer

[英]Convert CharBuffer to ByteBuffer

It is easy to convert a ByteBuffer to CharBuffer using ByteBuffer.asCharBuffer() .使用ByteBuffer.asCharBuffer()ByteBuffer转换为CharBuffer很容易。

How do I go in the other direction?我如何去另一个方向? Is there a simpler way than ByteBuffer Charset.encode(CharBuffer cb) ?有没有比ByteBuffer Charset.encode(CharBuffer cb)更简单的方法?

CharBuffer stores its data in an internal char[] and not byte[] therefore there is no underlying byte[] so there should be no simpler way. CharBuffer将其数据存储在内部char[]而不是byte[]因此没有底层byte[]所以应该没有更简单的方法。

Here's a suggestion.这是一个建议。

    CharBuffer yourCharBuffer = CharBuffer.wrap("Roland");

    ByteBuffer result = ByteBuffer.allocate(yourCharBuffer.length() * Character.BYTES);
    CharBuffer converter = result.asCharBuffer();
    converter.append(yourCharBuffer);

    System.out.println(Arrays.toString(result.array()));

The above snippet prints:上面的代码片段打印:

[0, 82, 0, 111, 0, 108, 0, 97, 0, 110, 0, 100] [0, 82, 0, 111, 0, 108, 0, 97, 0, 110, 0, 100]

I am getting the byte array out that is simultaniously backing the converter CharArray and the result ByteArray .我正在获取同时支持converter CharArrayresult ByteArray的字节数组。 It's as close as I can get to your requirements.它尽可能接近您的要求。 I may be missing something.我可能错过了一些东西。

Edit: following the suggestion by @Marcono1234 in the comment I am using ByteBuffer.allocate(yourCharBuffer.length() * Character.BYTES) to allocate a correctly sized buffer.编辑:按照@Marcono1234 在评论中的建议,我使用ByteBuffer.allocate(yourCharBuffer.length() * Character.BYTES)来分配正确大小的缓冲区。

If the code that filled your original CharBuffer could instead fill you byte buffer backed CharBuffer , it could be a bit simpler.如果填充原始CharBuffer的代码可以代替填充字节缓冲区支持的CharBuffer ,它可能会更简单一些。

And you own suggestion, Charset.encode(CharBuffer) , is simpler still.您自己的建议Charset.encode(CharBuffer)仍然更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM