D
D
DoctorSlon2017-07-02 23:52:22
Java
DoctorSlon, 2017-07-02 23:52:22

How to pack an int array into a char array as compactly as possible?

Hello!
The main question is in the title.
Now I use the following algorithm:
int -> byte[4] -> char[4
] the byte range is much smaller than the char range, but I can't think of an algorithm.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Moseychuk, 2017-07-03
@DoctorSlon

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class main {
  public static void main(String[] args) {
    int myint = 5120013;

    ByteBuffer b = ByteBuffer.allocate(4);
    b.asIntBuffer().put(myint);

    CharBuffer cb = b.asCharBuffer();

    char[] result  = new char[cb.limit()];
    cb.get(result);

    System.out.format("Char count: %d\n", result.length);
    System.out.print("0x");
    for(char c: result) {
      System.out.format("%04x", (int) c);
    }
    System.out.println();
  }
}
stdout
Char count: 2
0x004e200d

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question