Java simulation PHP pack and unpack class, packunpack
The examples in this article share with you the specific code for simulating PHP pack and unpack classes in java for your reference. The specific content is as follows:
Package qghl. intp. util; import java. io. IOException; import java. io. inputStream; public class PackUtil {/*** packaging String * is similar to the pack implementation in php in java ** @ param str * @ return */public static byte [] pack (String str) {int nibbleshift = 4; int position = 0; int len = str. length ()/2 + str. length () % 2; byte [] output = new byte [len]; for (char v: str. toCharArray () {byte n = (byte) v; if (n> = '0' & n <= '9') {n-= '0 ';} else if (n> = 'A' & n <= 'F') {n-= ('A'-10 );} else if (n> = 'A' & n <= 'F') {n-= ('A'-10);} else {continue ;} output [position] | = (n <nibbleshift); if (nibbleshift = 0) {position ++;} nibbleshift = (nibbleshift + 4) & 7 ;} return output ;} /*** unpack *** @ param is * @ param len * @ return * @ throws IOException */public static String unpack (InputStream is, int len) throws IOException {byte [] bytes = new byte [len]; is. read (bytes); return unpack (bytes );} /***** hexadecimal character extraction class in php unpack * @ param bytes * @ return */public static String unpack (byte [] bytes) {StringBuilder stringBuilder = new StringBuilder (""); if (bytes = null | bytes. length <= 0) {return null;} for (int I = 0; I <bytes. length; I ++) {int v = bytes [I] & 0xFF; String hv = Integer. toHexString (v); if (hv. length () <2) {stringBuilder. append (0);} stringBuilder. append (hv);} return stringBuilder. toString ();}}
The above is all the content of this article, and I hope it will help you learn java programming.
Articles you may be interested in:
- Python struct. unpack
- Character meanings of php pack and unpack
- How to Use the pack, unpack, and ord functions of the application instance for parsing the binary stream interface
- Php uses pack to process binary files
- Package)