본문 바로가기
프로그래밍 언어/c(일반)

BCD <-> DCB

by [Akashic Records] 개발의선지자 2024. 7. 18.

임의의 정수값을 읽어  BCD 변환 후 한비트 출력하는 예제 

 

#include <stdio.h>

void DectoHex(int Dec){
    int i =0;
    int  binary_value[100] = {0, };
    while (Dec > 0) {

        // storing remainder in binary array
        binary_value[i] = Dec % 2;
        Dec = Dec / 2;
        i++;
    }

    // printing binary array in reverse order
    while(i%4 != 0){
        binary_value[i] = 0;
        i++;
    }
    for (int j = i - 1; j >= 0; j--)
        printf("%d", binary_value[j]);
        
    for (int j = i - 1; j >= 0; j--){
    	if(binary_value[j] & 1){
        	printf("%d", j); // print only set bit 
 		}
    }
   
}

int main(){
    int n;
    scanf("%d", &n);
    DectoHex(n);
    return 0;
}