HexUtil工具类

  1. /** 
  2.  * 进制转化 
  3.  * @author  
  4.  * 
  5.  */  
  6. public class HexUtil {  
  7.   
  8.     /** 
  9.      * 二进制byte数组转十六进制byte数组 
  10.      * byte array to hex 
  11.      * 
  12.      * @param b byte array 
  13.      * @return hex string 
  14.      */  
  15.     public static String byte2hex(byte[] b) {  
  16.         StringBuilder hs = new StringBuilder();  
  17.         String stmp;  
  18.         for (int i = 0; i < b.length; i++) {  
  19.             stmp = Integer.toHexString(b[i] & 0xFF).toUpperCase();  
  20.             if (stmp.length() == 1) {  
  21.                 hs.append("0").append(stmp);  
  22.             } else {  
  23.                 hs.append(stmp);  
  24.             }  
  25.         }  
  26.         return hs.toString();  
  27.     }  
  28.   
  29.     /** 
  30.      * 十六进制byte数组转二进制byte数组 
  31.      * hex to byte array 
  32.      * 
  33.      * @param hex hex string 
  34.      * @return byte array 
  35.      */  
  36.     public static byte[] hex2byte(String hex)  
  37.              throws IllegalArgumentException{  
  38.         if (hex.length() % 2 != 0) {  
  39.             throw new IllegalArgumentException ("invalid hex string");  
  40.         }  
  41.         char[] arr = hex.toCharArray();  
  42.         byte[] b = new byte[hex.length() / 2];  
  43.         for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {  
  44.             String swap = "" + arr[i++] + arr[i];  
  45.             int byteint = Integer.parseInt(swap, 16) & 0xFF;  
  46.             b[j] = new Integer(byteint).byteValue();  
  47.         }  
  48.         return b;  
  49.     }  
  50.       
  51.     public static void main(String[] args) {  
  52.         String str1 = "abcedefghijklmnopqrstuvwxyz";  
  53.         //String str1 = "1";  
  54.         String hexStr = HexUtil.byte2hex(str1.getBytes());  
  55.         System.out.println(hexStr);  
  56.         String str2 = new String(HexUtil.hex2byte(hexStr));  
  57.         System.out.println(str2);  
  58.         System.out.println(str1.equals(str2));  
  59.     }  
  60.       
  61. }  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值