android数据转换tips

来源:互联网 发布:xboxonex 知乎 编辑:程序博客网 时间:2024/06/17 01:01

//将int类型转换成byte[]数组类型:

public byte[] intTobyteArr(){

        Integer a= 60855;
        byte[] b = new byte[4];
        b[0] = (byte)(a&0x000000ff);
        b[1] = (byte)((a&0x0000ff00)>>8);
        b[2] = (byte)((a&0x00ff0000)>>16);
        b[3] = (byte)((a&0xff000000)>>24);
            System.out.println(Byte.toString(b[0]));
            System.out.println(Byte.toString(b[1]));
            System.out.println(Byte.toString(b[2]));
            System.out.println(Byte.toString(b[3]));

}

又手残忘记移位了。

//四字节byte转换成long

public static long byte4ArrToLong(byte[] b){
        if(b.length != 4){
            return 0L;
        }
        long ret_l = 0L;
        ret_l+=(b[3]&0xff);
        ret_l+=(b[2]&0xff)<<8;
        ret_l+=(b[1]&0xff)<<16;
        ret_l+=(b[0]&0xff)<<24;
        
        return ret_l;
}

//四字节逆置转成long
public static long byte4ArrReverseToLong(byte[] b){
        if(b.length != 4){
            return 0L;
        }
        long ret_l = 0L;
        ret_l+=(b[0]&0xff);
        ret_l+=(b[1]&0xff)<<8;
        ret_l+=(b[2]&0xff)<<16;
        ret_l+=(b[3]&0xff)<<24;
        
        return ret_l;

}

//String转换成byte[]

String s= "abcdeg";

s.getBytes();

//字符转换成asc码

public static int getAsc(String st) {        byte[] gc = st.getBytes();        ascNum = (int) gc[0];        return ascNum;    }
//asc码转字符

public static char backchar(int backnum) {        strChar = (char) backnum;        return strChar;    }

0 0