본문 바로가기

개발자 모드/C언어

C언어 10진수로 받아서 2진수 배열에 넣기

728x90

#include <stdio.h>

int main()
{
	int input;

	int binary[20] = { 0, };
	
	printf("Input Number(Decimal: if you input zero then exit): "); 
	scanf_s("%d", &input);




	int position = 0;
	while (1)
	{
		binary[position] = input % 2;    // 2로 나누었을 때 나머지를 배열에 저장
		input = input / 2;             // 2로 나눈 몫을 저장

		position++;    // 자릿수 변경

		if (input == 0)    // 몫이 0이 되면 반복을 끝냄
			break;
	}

	// 배열의 요소를 역순으로 출력
	for (int i = position - 1; i >= 0; i--)
	{
		printf("%d", binary[i]);
	}

	printf("\n");

	return 0;
}


728x90