sooxin-JAVA

Java 16进制字符串与2进制字符串相互转换

public static String hexString2binaryString(String hexString) {
    if (hexString == null || hexString.length() % 2 != 0)
      return null;
    String bString = "", tmp;
    for (int i = 0; i < hexString.length(); i++) {
      tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16));
      bString += tmp.substring(tmp.length() - 4);
    }
    return bString;
  }
//------------------------------------------------------
  public static String binaryString2hexString(String bString) {
    if (bString == null || bString.equals("") || bString.length() % 8 != 0)
      return null;
    StringBuffer tmp=new StringBuffer();
    int iTmp = 0;
    for (int i = 0; i < bString.length(); i += 4) {
      iTmp = 0;
      for (int j = 0; j < 4; j++) {
        iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
      }
      tmp.append(Integer.toHexString(iTmp));
    }
    return tmp.toString();
  }

posted on 2007-05-08 15:10 sooxin 阅读(5330) 评论(1)  编辑  收藏 所属分类: JAVA

Feedback

# re: Java 16进制字符串与2进制字符串相互转换 2008-12-30 13:17 郑梦久

谢谢  回复  更多评论   



只有注册用户登录后才能发表评论。


网站导航: