在此程序中,您將學(xué)習(xí)使用Java中的函數(shù)實(shí)現(xiàn)二進(jìn)制數(shù)與十進(jìn)制數(shù)相互轉(zhuǎn)換。
public class BinaryDecimal {
public static void main(String[] args) {
long num = 110110111;
int decimal = convertBinaryToDecimal(num);
System.out.printf("%d 二進(jìn)制 = %d 十進(jìn)制", 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;
}
}運(yùn)行該程序時,輸出為:
110110111 二進(jìn)制 = 439 十進(jìn)制
public class DecimalBinary {
public static void main(String[] args) {
int num = 19;
long binary = convertDecimalToBinary(num);
System.out.printf("%d 十進(jìn)制 = %d 二進(jìn)制", 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, 余數(shù) = %d, 商 = %d\n", step++, n, remainder, n/2);
n /= 2;
binaryNumber += remainder * i;
i *= 10;
}
return binaryNumber;
}
}運(yùn)行該程序時,輸出為:
Step 1: 19/2, 余數(shù) = 1, 商 = 9 Step 2: 9/2, 余數(shù) = 1, 商 = 4 Step 3: 4/2, 余數(shù) = 0, 商 = 2 Step 4: 2/2, 余數(shù) = 0, 商 = 1 Step 5: 1/2, 余數(shù) = 1, 商 = 0 19 十進(jìn)制 = 10011 二進(jìn)制