본문 바로가기
Study & Edu/Algorithm

JAVA로 10진수 2진수 변환 (decimal to binary in JAVA)

by 댓츠굿 2017. 10. 5.


JAVA를 이용하여 10진수를 2진수로 변환하는 방법 6가지를 정리해보았다.



public class BinaryTest {
	public static void main(String[] args) throws Exception {
		
		//case1
		intToBinaryCase1(5);
		
		//case2
		String result = intToBinaryCase2(5);
		System.out.println("case2: "+ result);
		
		//case3
		intToBinaryCase3(5);
		
		//case4
		System.out.println("case4(1): " + intToBinaryCase4(5,4));
        System.out.println("case4(2): " + Integer.toString(5,2));
        
        //case5
        StringBuilder sb = new StringBuilder();
        intToBinaryCase5(5, sb);
        
        //case6
        System.out.println("case6: " + intToBinaryCase6(5));

	}
	
	
	
	public static void intToBinaryCase1(int n) {
		
		int bin[] = new int[16]; //change array size..
		int i = 0;
		
		while (n != 1) {
			bin[i++] = n%2;
			n = n/2;
		}

		bin[i] = n;
		
		for( int j=i; j>=0; --j ){
			System.out.println("case1: ["+j+"] = "+ bin[j]);
		}
		
	}
	
	
	public static String intToBinaryCase2(int n) {
		
		String s = "";
	    
		while (n > 0)
	    {
	        s = ( (n % 2 ) == 0 ? "0" : "1") + s;
	        //System.out.println("s:["+s+"]");
	        n = n / 2;
	        //System.out.println("n:["+n+"]");
	    }
	    
	    return s;
	}
	
	
	public static void intToBinaryCase3(int n) {
		
		int bin[] = new int[16]; //change array size..
		int i = 0;
		
		for( i=0; n!=1; i++ ) {
			
			bin[i] = n%2;
			n = n/2;
		}
		
		bin[i] = n;
		
		for( int j=i; j>=0; --j ){
			System.out.println("case3: ["+j+"] = "+ bin[j]);
		}
		
	}
	
	
	public static String intToBinaryCase4(int n, int sq) throws Exception {

		double pow = Math.pow(2, sq);
		StringBuilder binary = new StringBuilder();
		
		if (pow < n) {
			throw new Exception("The length must be big from number.");
		}
		
		int shift = sq - 1;
		
		for (; shift >= 0; shift--) {
			int bit = (n >> shift) & 1;
			
			if (bit == 1) {
				binary.append("1");
			} else {
				binary.append("0");
			}
		}
		
		return binary.toString();
	}
	
	
	private static void intToBinaryCase5(int n, StringBuilder sb) {

	    if (n > 0) {
	        sb.append(n % 2);
	        intToBinaryCase5(n >> 1, sb);
	    } else {
	        System.out.println("case5: "+sb.reverse().toString());
	    }
	}

	
	public static String intToBinaryCase6(int number){
	    
		StringBuilder sb = new StringBuilder();

	    if(number == 0)
	        return "0";
	    
	    while(number>=1){
	        sb.append(number%2);
	        number = number / 2;
	    }

	    return sb.reverse().toString();
	}

}


반응형