栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

java模拟PHP的pack和unpack类

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java模拟PHP的pack和unpack类

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

package qghl.intp.util;
 
import java.io.IOException;
import java.io.InputStream;
 
public class PackUtil{
 
    
    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;
    }
 
    
    public static String unpack(InputStream is, int len) throws IOException {
      byte[] bytes = new byte[len];
      is.read(bytes);
      return unpack(bytes);
    }
 
    
    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程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/43545.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号