Using the Arduino IDE, write code to convert any base-10 integer to its base-2 e
ID: 3668635 • Letter: U
Question
Using the Arduino IDE, write code to convert any base-10 integer to its base-2 equivalent. Your code should define the base-10 value as a variable, and print out to the serial port the final base-2 value. While there are many different approaches you could take to this problem, here are some suggestions and hints:
• The modulo operator (%) can be used to find the remainder of a division operation.
• Division using two integers will result in an integer that represents the quotient of the division operation (the remainder will be dropped).
• For this problem it is convenient to represent the binary number as an alphanumeric string, rather than a number. In languages like C, strings are just arrays of single characters, and are difficult to manipulate. An alternative is to use a String object (note the capital ‘S’ in String). It is quite easy to add new characters (in our case ‘1’ or ‘0’) to a String object using the ‘+’ operator (e.g. see https://www.arduino.cc/en/Tutorial/StringAdditionOperator).
Explanation / Answer
#include<stdio.h>
int main(){
long int decimalNumber,remainder,quotient;
int binaryNumber[100],i=1,j;
printf("Enter any decimal number: ");
scanf("%ld",&decimalNumber);
quotient = decimalNumber;
while(quotient!=0){
binaryNumber[i++]= quotient % 2;
quotient = quotient / 2;
}
printf("Equivalent binary value of decimal number %d: ",decimalNumber);
for(j = i -1 ;j> 0;j--)
printf("%d",binaryNumber[j]);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.