Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1096567
  • 博文数量: 252
  • 博客积分: 4561
  • 博客等级: 上校
  • 技术积分: 2833
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-15 08:23
文章分类

全部博文(252)

文章存档

2015年(2)

2014年(1)

2013年(1)

2012年(16)

2011年(42)

2010年(67)

2009年(87)

2008年(36)

分类:

2009-07-01 16:38:23

/**
        * Convert a byte array to a hex encoded string
        *
        * @param block
        * byte array to convert to hexString
        * @return String representation of byte array
        */

        public static String toHex(byte[] block)
        {
                StringBuffer buf = new StringBuffer();
  
                for (int i = 0; i < block.length; ++i)
                {
                        buf.append(hexits.charAt((block[i] >>> 4) & 0xf)); /* hell: high 4 bits */
                        buf.append(hexits.charAt(block[i] & 0xf)); /* hell: low 4 bits */
                }
  
                return buf + "";
        }
  
        /**
        * Convert a String hex notation to a byte array
        *
        * @param s
        * string to convert
        * @return byte array
        */

    public static byte[] fromHex(String s) {
                s = s.toLowerCase(Locale.ENGLISH);
                byte[] b = new byte[(s.length() + 1) / 2];
                int j = 0;
                int h;
                int nibble = -1;
  
                for (int i = 0; i < s.length(); ++i)
                {
                        h = hexits.indexOf(s.charAt(i));
                        if (h >= 0)
                        {
                                if (nibble < 0) /* hell: nibble store high 4 bits */
                                {
                                        nibble = h;
                                }
                                else
                                {
                                        b[j++] = (byte) ((nibble << 4) + h);
                                        nibble = -1;
                                }
                        }
                }
  
                if (nibble >= 0) {
                        b[j++] = (byte) (nibble << 4);
                }
  
                if (j < b.length) {
                        byte[] b2 = new byte[j];
                        System.arraycopy(b, 0, b2, 0, j);
                        b = b2;
                }
  
                return b;
        }
  
  
}

阅读(3722) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~