您的位置:首页 > 编程语言 > Java开发

java中字符跟字节转换 总结

2016-03-25 17:22 513 查看

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();
// System.out.println("tmp="+Arrays.toString(tmp));
/*
* int length = 0; if (tmp.length % 2 != 0) { length=(tmp.length+1)/2; }
* length=tmp.length;
*/
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);
// System.out.println("_b0="+_b0);
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));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: