- //整数到字节数组转换
- publicstaticbyte[]int2bytes(intn){
- byte[]ab=newbyte[4];
- ab[0]=(byte)(0xff&n);
- ab[1]=(byte)((0xff00&n)>>8);
- ab[2]=(byte)((0xff0000&n)>>16);
- ab[3]=(byte)((0xff000000&n)>>24);
- returnab;
- }
- //字节数组到整数的转换
- publicstaticintbytes2int(byteb[]){
- ints=0;
- s=((((b[0]&0xff)<<8|(b[1]&0xff))<<8)|(b[2]&0xff))<<8
- |(b[3]&0xff);
- returns;
- }
- //字节转换到字符
- publicstaticcharbyte2char(byteb){
- return(char)b;
- }
- privatefinalstaticbyte[]hex="0123456789ABCDEF".getBytes();
- privatestaticintparse(charc){
- if(c>='a')
- return(c-'a'+10)&0x0f;
- if(c>='A')
- return(c-'A'+10)&0x0f;
- return(c-'0')&0x0f;
- }
- //从字节数组到十六进制字符串转换
- publicstaticStringBytes2HexString(byte[]b){
- byte[]buff=newbyte[2*b.length];
- for(inti=0;i<b.length;i++){
- buff[2*i]=hex[(b[i]>>4)&0x0f];
- buff[2*i+1]=hex[b[i]&0x0f];
- }
- returnnewString(buff);
- }
- //从十六进制字符串到字节数组转换
- publicstaticbyte[]HexString2Bytes(Stringhexstr){
- byte[]b=newbyte[hexstr.length()/2];
- intj=0;
- for(inti=0;i<b.length;i++){
- charc0=hexstr.charAt(j++);
- charc1=hexstr.charAt(j++);
- b[i]=(byte)((parse(c0)<<4)|parse(c1));
- }
- returnb;
- }
java二进制,字节数组,字符,十六进制,BCD编码转换
最新推荐文章于 2022-07-26 20:45:12 发布