Fast ByteBuffer for CharBuffer or char []

What is the fastest way to convert java.nio.ByteBuffer ato (newly created) CharBuffer bor char[] b.

It is important that a[i] == b[i]. This means that they do not a[i]and a[i+1]together make up the meaning of b[j]what getChar(i)will be done, but the meanings must be “disseminated”.

byte a[] = { 1,2,3, 125,126,127, -128,-127,-126 } // each a byte (which are signed)
char b[] = { 1,2,3, 125,126,127,  128, 129, 130 } // each a char (which are unsigned)

Note that it byte:-128has the same (lower 8) bits as char:128. Therefore, I assume that the “best” interpretation will be the same as I noted above, because the bit is the same.

After that, I will also need a translation the other way around : the most efficient way to get it back char[]or java.nio.CharBufferback to java.nio.ByteBuffer.

+5
source share
3 answers

So, you want to convert using ISO-8859-1 encoding.

I am not saying anything about efficiency, but at least write it pretty short:

CharBuffer result = Charset.forName("ISO-8859-1").decode(byteBuffer);

Other direction:

ByteBuffer result = Charset.forName("ISO-8859-1").encode(charBuffer);

Please measure this against other solutions. (To be fair, the part Charset.forNameshould not be included, and should only be executed once, and not for each buffer again.)

From Java 7, there is also a StandardCharsets class with pre-created instances of Charset, so you can use

CharBuffer result = StandardCharsets.ISO_8859_1.decode(byteBuffer);

and

ByteBuffer result = StandardCharsets.ISO_8859_1.encode(charBuffer);

. ( , , , .)

+11

@Ishtar's, , .

, ByteBuffer, .

ByteBuffer bb = ...
byte[] array = bb.array();
char[] chars = new char[bb.remaining()];
for (int i = 0; i < chars.length; i++)
    chars[i] = (char) (array[i + bb.position()] & 0xFF);
+6

CharBuffer, . , , CharBuffer char [], " "; ByteBuffer.get() ( ), char ( : , , , , 128-255 , 0xFF80 - 0xFFFF; 7- ASCII) .

0
source

All Articles