Hi all. Still trying to get going in c. I am learning c because I want to get back into programming microcontrollers, which I previously did in assembly. I wanted to make something fairly tight in terms of program memory and RAM to show me an output in binary form. It just kind of helps when you are troubleshooting a file register or serial interface when you can see the actual bit values (on a small LCD for a micro-controller) and compare it to a datasheet.
Please evaluate my below code for efficiency. What could I do better? Is it fairly efficient, or is it bloated?
Code:
#include <stdio.h>
#include <math.h>
int main()
{
int i;
int decimaltoconvert;
int convertingarray[7];
int convertingarray2[7];
//this for statement calculated the 2^i for use in the converting for statement that follows
//it only needs to be done once, at the top of a program, to set up for subsequent conversion routines
for (i=0;i<8;i++) {
convertingarray[i] = pow(2,i);
}
while(1) { //start of infinite while loop
printf("\nEnter a decimal 255 or below to be output as binary.\n");
scanf("%d",&decimaltoconvert);
if (decimaltoconvert < 255) { //make sure this is less than 255
//this for statement will do an integer division of the decimal / 2^i and set the indexed array = to 1 or 0
for (i=7;i>=0;i--) {
convertingarray2[i] = decimaltoconvert/convertingarray[i]; //do integer division
if(convertingarray2[i] == 1) { //if is == 0, subtracting will be negative.
decimaltoconvert = decimaltoconvert - convertingarray[i];
}
printf("%d",convertingarray2[i]);
}
} //close bracket of "<255" if statement
else{ //this else statement will execute if decimaltoconvert > 255
printf("The number is over 255. Try again!");
}
} //close bracket for infinite while loop
}
Also, how might I go about putting that into a function that I could call?
Thanks!