当前位置:首页 > PHP教程 > PHP高级教程

java模拟PHP的pack和unpack类

本文实例为大家分享了java模拟php的pack和unpack类的具体代码,供大家参考,具体内容如下

package qghl.intp.util; import java.io.ioexception; import java.io.inputstream; public class packutil{ /** * 打包字符串 * 类似php中pack在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; } /** * 16进制的字符解压 类php中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); } /*** * 16进制的字符解压 类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(); } }

以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!