Search code examples
javamemorytypescopyprimitive

How to copy primitive type memory in Java?


I have two chars = 4 bytes, that representing integer value (geted from stream).

How can I copy these into a primitive int variable?


Solution

  • You are better off reading 4 bytes as an int from the start. However to turn two char into an int you can use

    char ch1, ch2;
    int i = (ch1 << 16) + ch2; // or ch2 << 16 + ch1
    

    You need to know whether the order is little or big endian.