English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java 기본 튜토리얼

Java 흐름 제어

Java 배열

Java 지향 객체(I)

Java 지향 객체(II)

Java 지향 객체(III)

Java 예외 처리

Java 목록(List)

Java Queue(큐)

Java Map集合

Java Set集合

Java 입력 출력(I/O)

Java Reader/Writer

Java 다른 주제

Java 프로그램 이진수와 십진수相互 변환

Java 예제 모든 것

이 프로그램에서는 Java에서 함수를 사용하여 이진수와 십진수를相互 변환하는 방법을 배울 수 있습니다.

예제1:이진수를 십진수로 변환하는 프로그램

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 십진수

예제2:십진수를 이진수로 변환하는 프로그램

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("단계 %d: %d/2, remainder = %d, quotient = %d\n", step++, n, remainder, n/2);
            n /= 2;
            binaryNumber += remainder * i;
            i *= 10;
        }
        return binaryNumber;
    }
}

이 프로그램을 실행할 때, 출력은 다음과 같습니다:

단계 1: 19/2, remainder = 1, quotient = 9
단계 2: 9/2, remainder = 1, quotient = 4
단계 3: 4/2, remainder = 0, quotient = 2
단계 4: 2/2, remainder = 0, quotient = 1
단계 5: 1/2, remainder = 1, quotient = 0
19 십진 = = 10011 이진

Java 예제 모든 것