十进制转二进制、八进制
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(10));//1010
System.out.println(Integer.toOctalString(10));//12
System.out.println(Integer.toHexString(10));//a
}
十进制转其他进制
目前没找到封装的api方法,不过可以用除基取余法,同理其他转十进制也可以自己写方法。
public static void main(String[] args) {
int a = 11;
StringBuffer sb = new StringBuffer();
//除基取余法
while (a != 0) {
sb.append(a % 3);//取余
a /= 3;//除基
}
sb.reverse();
System.out.println(sb.toString());//102
}
其他转十进制
public static void main(String[] args) {
System.out.println(Integer.parseInt("1010", 2));//10
System.out.println(Integer.parseInt("1010", 8));//520
System.out.println(Integer.parseInt("a", 16));//10
}
public static void main(String[] args) {
String str = "101";
int res = 0;
for (int i = 0; i < str.length(); i++) {
res += Math.pow(2, i) * (str.charAt(i) - '0');
}
System.out.println(res);//5
}