String and Byte
由于近期程序中经常要用到进制转换,于是把这些方法抽取,方便以后直接使用
/**
* 字符串1345642123 → byte []l={1,3,4,5,6,4,2,1,2,3}
**/
public static byte[] StringtoSingleByte(String sPhone) {
byte[] bPhone = sPhone.getBytes();
for (int i = bPhone.length - 1; i >= 0; i--) {
bPhone[i] -= (byte) '0';
}
return bPhone;
}
/**
* 字符串124312 → byte []hexbyte={0x12,0x43,0x12}
**/
public static byte[] StringtoHexBytes(String src) {
if (null == src || 0 == src.length()) {
return null;
}
byte[] ret = new byte[src.length() / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < (tmp.length / 2); i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
public 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;
}
/**
* 字符串 124312 → byte []hexbyte={12,43,12}
**/
public static byte[] StringtoByte(String a){
int length = a.length();
byte []BYTE = new byte[a.length()/2];
if(length%2!=0){
a="0"+a;
BYTE=new byte[a.length()/2];
length = a.length();
}
for(int i=length;i>1;i=i-2){
BYTE[i/2-1]=Byte.parseByte(a.substring(i-2, i));
}
return BYTE;
}
public static void main(String[] args) {
String a ="12345678";
byte [] b=StringtoHexBytes(a);
System.out.println(Arrays.toString(b));
}