各种转码总结

来源:互联网 发布:学校机房网络限制 编辑:程序博客网 时间:2024/06/03 17:47
 

/**
  * 二进制转十六进制
  *
  * @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;
 }

原创粉丝点击