-1

I want to convert my C program to a AVR Assembly program thats converts the decimal number into a binary number. This program is specified for the Atmega32a. Can someone help me ? Thankyou. This is the program that i need to convert to Asssembly:

    int main()  
{  
    int num, bin = 0, rem = 0, place = 1;  
  
    printf("Enter a decimal number\n");  
    scanf("%d", &num);  
  
    printf("\nBinary equivalent of %d is ", num);  
    while(num)  
    {  
        rem   = num % 2;  
        num   = num / 2;  
        bin   = bin + (rem * place);  
        place = place * 10;  
    }  
    printf("%d\n", bin);  
  
    return 0;  
} 
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Nar
  • 1
  • Presumably you actually want `unsigned int`, because `num % 2` for negative numbers will be 0 or `-1`. Also, normally one would convert to a string of ASCII digits, not a huge decimal number that has the same base-10 digits as the original number has base-2 digits. You eventually want to print it, so you're just making things harder by aiming to eventually use `printf("%d\n")` instead of `puts` on a `char buffer[17]` – Peter Cordes Oct 08 '21 at 22:37
  • Use a compiler. Converting source code to assembly is what compilers do. – klutt Oct 12 '21 at 07:00

1 Answers1

1

scanf, printf & atmega are not very good friends :)

There is nothing like a decimal integer only an integer.

Converting to binary means that you want string containing '0' and '1' characters.

Use functions for this kind of tasks. This function is opmized for 8 bits AVR architecture.

char *tobin(char *str, unsigned val)
{
    char *buff = str;
    unsigned mask = 1ULL << (sizeof(mask) * 8 - 1);
    char start = 0;
    while(mask)
    {   
        char bit = !!(val && mask);
        if(!start) start = bit;
        if(start) 
            *buff++ = bit + '0';
        mask >>= 1;
    }
    *buff = 0;
    return str;
}

Assembly you have in this link: https://godbolt.org/z/osW6YYKbv

0___________
  • 60,014
  • 4
  • 34
  • 74