This article mainly introduces the pack and unpack types of PHP simulation in java, for more information about how to simulate the pack and unpack classes in java, see the examples in this article.
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.