java int转byte,long转byte

int  a; a在内存中占四个字节
long b; b在内存中占八个字节,
把b强制转换成a, 就会少掉四个字节的信息,如果b的值不超过int型能表示的最大值,则不会有信息丢失,但是如果b的值超过了int 型能表示的最大值,高位的那四个字节的数据就会丢失

和0xff与操作(a&0xff)为了让负的变为正的,与操作是:相同为1,不同为0

所以int转换byte的的时候:
View Code
byte[] returnInt = new byte[4];
        returnInt[0] = (byte)((intValueParm >>> 24) & 0xFF);
        returnInt[1] = (byte)((intValueParm >>> 16) & 0xFF);
        returnInt[2] = (byte)((intValueParm >>>  8) & 0xFF);
        returnInt[3] = (byte)((intValueParm >>>  0) & 0xFF);
        return returnInt;

long转换为byte的时候:

View Code
byte[] returnInt = new byte[8];
        returnInt[0] = (byte)((longValueParm >> 56) & 0xFF);
        returnInt[1] = (byte)((longValueParm >>> 48) & 0xFF);
        returnInt[2] = (byte)((longValueParm >>> 40) & 0xFF);
        returnInt[3] = (byte)((longValueParm >>> 32) & 0xFF);
        returnInt[4] = (byte)((longValueParm >>> 24) & 0xFF);
        returnInt[5] = (byte)((longValueParm >>> 16) & 0xFF);
        returnInt[6] = (byte)((longValueParm >>>  8) & 0xFF);
        returnInt[7] = (byte)((longValueParm >>>  0) & 0xFF);
        return returnInt;

这段代码是一个同事写的,各种百度才看懂!基础知识不过关啊



posted @ 2012-11-08 16:48  softwa  阅读(352)  评论(0编辑  收藏  举报