首页 > 编程 > Java > 正文

Java中进制转换

2019-11-10 23:18:00
字体:
来源:转载
供稿:网友

  计算机只能识别二进制数,在实际应用中存在十进制、八进制和十六进制数。java中提供了对应的API来实现进制转换。

十进制数转换成其他进制数。 //十进制数转换成二进制、十六进制、八进制 System.out.PRintln(Integer.toBinaryString(112)); System.out.println(Integer.toHexString(112)); System.out.println(Integer.toOctalString(112)); //二进制、八进制、十六进制转换成十进制 System.out.println(Integer.parseInt("111001", 2)); System.out.println(Integer.parseInt("27", 8)); System.out.println(Integer.parseInt("A8", 16));

基本数据类型转换成字节数组 例如8143二进制数为00000000 00000000 00011111 11001111 第一个小端字节:8143 >>0*8 &&0xff = 11001111,无符号数则为207,有符号数为11001111–>11001110–>00110001 为-49。 第二个小端字节:8143>>1*8 &&0xff = 00011111 = 31 第三个小端字节:8143>>2*8 &&0xff = 00000000 = 0 第四个小端字节: 8143>>3*8 &&0xff = 00000000 = 0

小端是指低位字节位于低地址端即为起始地址,高位字节位于高地址端。大端则刚好相反。

字符串转换成字节数组

String str; byte[] bytes = str.getBytes();字节数组转换成字符串 byte[] bytes = new byte[N]; String s = new String(bytes); String s = new String(bytes, encode); //encode 为utf-8,gb2312等 //整型转换成byte数组 private static byte[] Int2Bytes(int n) { byte[] bytes = new byte[4]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) ((n >> (i * 8)) & 0xff); } return bytes; } //byte数组转换成整型 private static int Bytes2Int(byte[] bytes) { int result = 0; for (int i = 0; i < bytes.length; i++) { result += ((bytes[i] & 0xff) << i * 8); } return result; }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表