各种进制转换

来源:互联网 发布:苹果实用软件推荐 编辑:程序博客网 时间:2024/06/06 13:59

byte  转字符串

    public static String hexString(byte b) {String hex = Integer.toHexString(b & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}return hex;}

byte[] 转 字符串(这里提供两种方法)

    public static String hexString(byte[] b) {StringBuffer sb = new StringBuffer();for (int i = 0; i < b.length; i++) {String hex = Integer.toHexString(b[i] & 0xFF);if (hex.length() == 1) {hex = '0' + hex;}sb.append(hex.toUpperCase());}return sb.toString();}


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();}



转换十六进制编码为字符串  

    public static String toStringHex(String s) {          if ("0x".equals(s.substring(0, 2))) {              s = s.substring(2);          }          byte[] baKeyword = new byte[s.length() / 2];          for (int i = 0; i < baKeyword.length; i++) {              try {                  baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(                          i * 2, i * 2 + 2), 16));              } catch (Exception e) {                  e.printStackTrace();              }          }          try {              s = new String(baKeyword, "utf-8");//UTF-16le:Not          } catch (Exception e1) {              e1.printStackTrace();          }          return s;      }

String类型转换byte[]

public static byte[] hexStringToByte(String hex) {    int len = (hex.length() / 2);       byte[] result = new byte[len];       char[] achar = hex.toCharArray();       for (int i = 0; i < len; i++) {        int pos = i * 2;        result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));       }       return result;   }

private static byte toByte(char c) {       byte b = (byte) "0123456789ABCDEF".indexOf(c);       return b;   }  



16进制转10进制

String X10 = Integer.valueOf(X16,16).toString();

10进制转2进制

String X2 = Integer.toBinaryString(Integer.parseInt(X10));


0 0