JAVA位运算、进制转换、byte数组转换、JAVA数据类型取值范围

来源:互联网 发布:怎么在阿里云里备案 编辑:程序博客网 时间:2024/06/06 02:24

位运算

~ 按位非(NOT) & 按位与(AND) | 按位或(OR)
^ 按位异或(XOR >> 右移 >>> 无符号右移 <<左移 


进制转换

16进制0x   8进制0   切记是数字0

//十进制转成十六进制:Integer.toHexString(n1);

//十进制转成八进制:Integer.toOctalString(n1);

//十进制转成二进制:Integer.toBinaryString(12);

//十六进制转成十进制:Integer.valueOf("FFFF",16).toString();

//N进制转成十进制:Integer.valueOf("****",N).toString();

//16进制直接转2进制:Integer.toBinaryString(0xfdac)


ps:
parseInt("99", 8) 

越界异常,比如你指定的基数为8,解析的字符串却包含"9"就会抛出NumberFormatException。



byte 与 int 的相互转换 


1.//byte 与 int 的相互转换  2.public static byte intToByte(int x) {  3.    return (byte) x;  4.}  
5.public static int byteToInt(byte b) {  6.Java 总是把 byte 当做有符处理;我们可以通过将其和 0xFF 进行二进制与得到它的无符值  7.    return b & 0xFF;  8.}


byte数组与int之间转换
1.//byte 数组转int2.public static int byteArrayToInt(byte[] b) {  3.    return   b[3] & 0xFF |  4.            (b[2] & 0xFF) << 8 |  5.            (b[1] & 0xFF) << 16 |  6.            (b[0] & 0xFF) << 24;  
7.public static byte[] intToByteArray(int a) {  8.    return new byte[] {  9.        (byte) ((a >> 24) & 0xFF),  10.        (byte) ((a >> 16) & 0xFF),     11.        (byte) ((a >> 8) & 0xFF),     12.        (byte) (a & 0xFF)  

第二种方法

  /**     * byte数组转int     */    public static int bytes2Int(byte[] b) {          ByteBuffer buffer = ByteBuffer.allocate(4);        buffer.put(b);        buffer.flip();        return buffer.getInt();    }    /**     * int转byte数组     */    public static byte[] int2Bytes(int a) {        ByteBuffer buffer = ByteBuffer.allocate(4);        buffer.putInt(a);        return buffer.array();    }

byte数组与long之间转换

分配一个新的字节缓冲区,因为long的字节长度为8,所以allocate一定不能小于8

 buffer.putLong(0, x);   8 个包含给定 long 值的字节按照当前的字节顺序写入到此缓冲区的给定索引处0的位置。allocate缓冲区字节大小

1.private static ByteBuffer buffer = ByteBuffer.allocate(8);   2.//byte 数组与 long 的相互转换  3.   public static byte[] longToBytes(long x) {  4.       buffer.putLong(0, x);  5.       return buffer.array();  //返回此缓冲区的byte数组6.   }  
7.   public static long bytesToLong(byte[] bytes) {  8.       buffer.put(bytes); //将字节数组放入缓冲区中 9.       buffer.flip();//一定要写不然报错,反转此缓冲区 10.       return buffer.getLong();  //读取缓冲区8个字节组成long值


扩展

byte[] seq=new byte[4];

for(int i=0;i<seq.length;i++){

seq[i]=(byte)new Random().nextInt(127);

0127随机整数[1,59,15,124]

}

int a=0xfdac;      返回十进制64940

String binaryString = Integer.toBinaryString(a);二进制

 1111110110101100

int parseInt = Integer.parseInt(a+"", 19);

0*0+4*19+9*19^2+4*19^3+6*19^4=818627



JAVA数据类型取值范围


Char           2字节(64位)      0~65535  




阅读全文
0 0