在此程序中,您将学习使用Java中的函数实现二进制数与十进制数相互转换。
public class BinaryDecimal { public static void main(String[] args) { long num = 110110111; int decimal = convertBinaryToDecimal(num); System.out.printf("%d 二进制 = %d 十进制", num, decimal); } public static int convertBinaryToDecimal(long num) { int decimalNumber = 0, i = 0; long remainder; while (num != 0) { remainder = num % 10; num /= 10; decimalNumber += remainder * Math.pow(2, i); ++i; } return decimalNumber; } }
运行该程序时,输出为:
110110111 二进制 = 439 十进制
public class DecimalBinary { public static void main(String[] args) { int num = 19; long binary = convertDecimalToBinary(num); System.out.printf("%d 十进制 = %d 二进制", num, binary); } public static long convertDecimalToBinary(int n) { long binaryNumber = 0; int remainder, i = 1, step = 1; while (n!=0) { remainder = n % 2; System.out.printf("Step %d: %d/2, 余数 = %d, 商 = %d\n", step++, n, remainder, n/2); n /= 2; binaryNumber += remainder * i; i *= 10; } return binaryNumber; } }
运行该程序时,输出为:
Step 1: 19/2, 余数 = 1, 商 = 9 Step 2: 9/2, 余数 = 1, 商 = 4 Step 3: 4/2, 余数 = 0, 商 = 2 Step 4: 2/2, 余数 = 0, 商 = 1 Step 5: 1/2, 余数 = 1, 商 = 0 19 十进制 = 10011 二进制