/**
* 获取字节某几位上的值 如要获取bit0,则i=0
* @param b 传入的字节
* @param i 第几位(范围0-7)
* @param count 要几位的
* @return short
*/publicstaticshortgetBit(byte b,int i,int count){if(count >7|| count <0){return b;}return(short)((b >> i)&((int)(Math.pow(2,count))-1));}
字节与int互转
将四字节转为int
//byte[4]转int 小端模式publicstaticintbyte42IntLittle(byte[] bt){if(bt.length !=4){return0;}byte[] b =newbyte[4];
b[3]= bt[0];
b[2]= bt[1];
b[1]= bt[2];
b[0]= bt[3];int result =0;for(int i =0; i < b.length; i++){int tmpVal =(b[i]<<(8*(3- i)));switch(i){case0:
tmpVal = tmpVal &0xFF000000;break;case1:
tmpVal = tmpVal &0x00FF0000;break;case2:
tmpVal = tmpVal &0x0000FF00;break;case3:
tmpVal = tmpVal &0x000000FF;break;}
result = result | tmpVal;}return result;}
将int转为字节
int转为一个字节 ,可强转,但是可能会导致精度丢失 (byte) aInt
将int转为四字节数组
/**
* int转为四字节
* @param n int
* @return 返回字节
*/publicstaticbyte[]Int2Bytes(int n){byte[] b =newbyte[4];
b[0]=(byte)(n &0xff);
b[1]=(byte)(n >>8&0xff);
b[2]=(byte)(n >>16&0xff);
b[3]=(byte)(n >>24&0xff);return b;}
有个字符串“AE”,转为int
int aa =Integer.parseInt("AE",16);
有个字符串“1100",转为int
int aa =Integer.parseInt("1101",2);
字符串与byte数组
十六进制字节数组转汉字字符串 (GBK编码)
byte[] a =newbyte[]{(byte)0xC9,(byte)0xE8,(byte)0xB1,(byte)0xB8,(byte)0xD2,(byte)0xEC,(byte)0xB3,(byte)0xA3};String result =null;try{
result =newString(a,"GBK");}catch(UnsupportedEncodingException e){
e.printStackTrace();}System.out.println(result);