8421BCD編碼,用於存儲手機號碼,每2位手機號碼存儲於一個byte中,詳細轉換如下:
比如手機號碼 13129911472 ,13拆開為1和3,1對應2進制為 0000 0001,3對應2進制為 0000 0011,合並只有為 0001 0011,對應byte為 19,對應16進制為 0x13
byte轉10進制:
byte b=19; int a=b&0xFF; //byte轉int 此時 a=19 byte b=-103; int a=b&0xFF; //byte轉int 此時a=153
10進制轉16進制:
int a=19; String hex=Integer.toHexString(a); //10進制轉16進制,此時hex =13
byte數組轉16進制:
public 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)//小於16會補0 hs = hs + "0" + stmp; else hs = hs + stmp; } return hs.toUpperCase(); }
16進制字符串轉10進制:
String str="AC"; int num=Integer.parseInt(str,16);//此時 num 為172 byte b=(byte)num; //此時byte 為 -84
16進制字符串轉byte數組
public static byte[] hex2byte(String content) { byte[] mtemp=new byte[content.length()/2];//初始化byte數組,長度為lenth/2,每2個表示一個byte int j=0; for (int n=0; n<content.length(); n=n+2) {//每次增加2 String sTemp=content.substring(n,n+2);//截取每2個 //0xca-256=-54 mtemp[j]=(byte)Integer.parseInt(sTemp, 16);//先轉成10進制int,然后再轉成byte j++; } return mtemp; }
字符串獲取特定編碼字節數組:
public static byte[] getBytesArray(String str,String changeToCharset) throws UnsupportedEncodingException { return str.getBytes(changeToCharset); }
對字節數組通過特定編碼獲取字符串:
public static String bytesToString(byte[] bs,String changeToCharset) throws UnsupportedEncodingException { return new String(bs,changeToCharset); }