现在的位置: 首页 > 综合 > 正文

各种转码总结

2013年01月10日 ⁄ 综合 ⁄ 共 883字 ⁄ 字号 评论关闭

 

/**
  * 二进制转十六进制
  *
  * @param b
  * @return
  */
 private static String byte2hex(byte[] b) {
  String hs = "";
  String stmp = "";
  for (int n = 0; n < b.length; n++) {
   stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
   if (stmp.length() == 1) {
    hs = hs + "0" + stmp;
   } else {
    hs = hs + stmp;
   }
  }
  return hs.toUpperCase();
 }

 /**
  * 十六进制字符串转化为2进制
  *
  * @param hex
  * @return
  */
 private static byte[] hex2byte(String hex) {
  byte[] ret = new byte[8];
  byte[] tmp = hex.getBytes();
  for (int i = 0; i < 8; i++) {
   ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
  }
  return ret;
 }

 /**
  * 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF
  *
  * @param src0
  *            byte
  * @param src1
  *            byte
  * @return byte
  * @see [类、类#方法、类#成员]
  */
 private static byte uniteBytes(byte src0, byte src1) {
  byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
    .byteValue();
  _b0 = (byte) (_b0 << 4);
  byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
    .byteValue();
  byte ret = (byte) (_b0 ^ _b1);
  return ret;
 }

抱歉!评论已关闭.