本文实例为大家分享了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程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
[ACTF2020 新生赛]Include 1【文件包含】【读取代码】
算法题解 - 牛客编程巅峰赛S1第6场 - 黄金&钻石&王者组
推荐一个程序员必备网站之一:Dev Hints ,非常实用!
网友评论