Chinaunix首页 | 论坛 | 博客
  • 博客访问: 242782
  • 博文数量: 27
  • 博客积分: 4010
  • 博客等级: 上校
  • 技术积分: 410
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-10 13:39
文章分类

全部博文(27)

文章存档

2010年(17)

2009年(2)

2008年(8)

我的朋友
最近访客

分类: Java

2008-08-14 19:05:51

之所以要在这两者之间转化,最初的目的是为了能让字节数组存储到MySQL数据库中,因为MySQL里不支持字节数组(byte[])类型,我唯一能想到的方法就是把字节数组转化为十六进制的字符串存储,读取的时候反向转化即可。

用到了之前写过的byte[]转字符串的方法,只要再写一个字符串转byte[]的方法就可以了,源代码如下:

/**
 * @author wangtao
 * @version 2008.8.14
 */
public class Util {
    public static char[] hexDigits =
    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * @notes 字节数组转化为字符串
     * @param bytes
     * @return String
     */
    public static String toHexString(byte[] bytes) {
        char[] chars = new char[bytes.length * 2];

        for (int i = 0; i < bytes.length; i++) {
            int b = bytes[i];
            chars[i * 2] = Util.hexDigits[(b & 0xF0) >> 4];
            chars[i * 2 + 1] = Util.hexDigits[b & 0x0F];
        }

        return new String(chars);
    }
   
    /**
     * @notes 字符串转化为字节数组
     * @param str
     * @return byte[]
     */
    public static byte[] toByteArray(String str) {
        int length = str.length() / 2;
        byte[] bytes = new byte[length];
        byte[] source = str.getBytes();

        for (int i = 0; i < bytes.length; ++i) {
            byte bh = Byte.decode("0x" + new String(new byte[]{source[i * 2]})).byteValue();
            bh = (byte)(bh << 4);
            byte bl = Byte.decode("0x" + new String(new byte[]{source[i * 2 + 1]})).byteValue();
            bytes[i] = (byte)(bh ^ bl);
        }
       
        return bytes;
    }
}
阅读(5407) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~