首页 > 编程语言 > 详细

java中String byte HexString的转换

时间:2015-09-02 18:34:28      阅读:250      评论:0      收藏:0      [点我收藏+]

原文:http://blog.sina.com.cn/s/blog_62e9ec530101ebv6.html

HexString——>byte
 public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); 
        }
        return d;
    }
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
byte——>String
 
 public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
byte——>hexString
 
public   String printHexString( byte[] b) {
String a = "";
  for (int i = 0; i < b.length; i++) { 
    String hex = Integer.toHexString(b[i] & 0xFF); 
    if (hex.length() == 1) { 
      hex = ‘0‘ + hex; 
    }
   
    a = a+hex;
  } 
       return a;
}

 

java中String byte HexString的转换

原文:http://www.cnblogs.com/pwenlee/p/4779039.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!