So I have the task of creating a program that will take exactly two arguments, the second being an integer. I have to convert that integer to a binary value and then print out the location of the least significant "1" bit. Below is the code I currently have that successfully converts the integer in to binary. I wanted to fill an array with the binary value and then cycle from the last position and decrement a counter until I encountered a "1" and then print out the position of that bit by subtracting the overall length of the array from the current position in the array.
#include <stdio.h>
#include <stdlib.h>
int convert(int);
int main(int argc, char *argv[])
{
int bin;
int n = atoi(argv[2]);
if (argc<2)
{
printf("\nNot Enough Arguments.");
}
if (argc>2)
{
printf("\nToo Many Arguments.");
}
if (argc==2)
{
scanf("%d", &n);
bin = convert(n);
lessbit[] = bin;
}
return 0;
}
int convert(int n)
{
if (n == 0)
{
return 0;
}
else
{
return (n % 2 + 10 * convert(n / 2));
}
}
Numbers are stored in the machine as binary so you do not need to convert anything.
Here is a small demo program that will print the position of the first 1 moving from right to left (least significant 1 bit).
#include <stdio.h>
#include <stdlib.h>
int main(int arc, char* argv[]) {
if(argc != 2)
exit(EXIT_FAILURE);
int bin = atoi(argv[1]);
unsigned counter = 0;
while(bin % 2 == 0) {
bin >>= 1;
counter++;
}
printf("%u\n", counter);
return 0;
}
This code prints out the exponent base 2. So if the number is 8 which is 1000 in binary the output will be the position of the 1 which is 3 (since it's in the 2^3 position).