只要掌握其他进制到10进制的相互转换, 就可以借助10进制完成各种进制之间的相互转换。
1 JavaScript实现
bitConverter.js
let num = 15
console.log("10进制转8进制结果为: " + num.toString(8))
console.log("10进制转16进制结果为: " + num.toString(16))
console.log("10进制转2进制结果为: " + num.toString(2))
let binStr = "0101"
let octStr = "012"
let hexStr = "0x1a2f"
console.log("2进制转10进制结果为: " + parseInt(binStr, 2))
console.log("8进制转10进制结果为: " + parseInt(octStr, 8))
console.log("8进制转10进制结果为: " + parseInt(hexStr, 16))
2 python实现
bitConverter.py
num = 10
print("10进制转2进制结果为:{}".format(bin(10)))
print("10进制转8进制结果为:{}".format(oct(10)))
print("10进制转16进制结果为:{}".format(hex(10)))
bin_str = "0b0110"
oct_str = "0o15"
hex_str = "0x1a2f"
print("2进制转10进制结果为:{}".format(int(bin_str, 2)))
print("2进制转10进制结果为:{}".format(int(oct_str, 8)))
print("2进制转10进制结果为:{}".format(int(hex_str, 16)))
3 java实现
BitConverter.Java
public class BitConverter {
public static void main(String[] args) {
Integer num = 10;
System.out.println("10进制转2进制结果为:" + Integer.toBinaryString(num));
System.out.println("10进制转8进制结果为:" + Integer.toOctalString(num));
System.out.println("10进制转16进制结果为:" + Integer.toHexString(num));
string binStr = "1001";
string octStr = "16";
string hexStr = "1a1f";
System.out.println("2进制转10进制结果为:" + Integer.valueOf(binStr, 2));
System.out.println("2进制转10进制结果为:" + Integer.valueOf(octStr, 8));
System.out.println("2进制转10进制结果为:" + Integer.valueOf(hexStr, 16));
}
}
4 go实现
bitConverter.go
package main
import ("fmt"; "strconv")
func main() {
res2 := strconv.FormatInt(4, 2)
res8 := strconv.FormatInt(8, 8)
res16 := strconv.FormatInt(15, 16)
fmt.Println("10进制转2进制结果为:" + res2)
fmt.Println("10进制转8进制结果为:" + res8)
fmt.Println("10进制转16进制结果为:" + res16)
parseInt2, _ := strconv.ParseInt("1000", 2, 64)
parseInt8, _ := strconv.ParseInt("20", 8, 64)
parseInt16, _ := strconv.ParseInt("e", 16, 64)
fmt.Println("2进制转10进制结果为:" + parseInt2)
fmt.Println("8进制转10进制结果为:" + parseInt8)
fmt.Println("16进制转10进制结果为:" + parseInt16)
}
|