Simulate PHP pack and unpack classes in java

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.