-
How to print binary
when I type a integer this program should give me the binary for that integer printed. I have this so far
--------------------------------------------
#include <stdio.h>
main()
{
int i;
printf ("Please type in your number\n");
scanf ("%d", &i);
print_binary (i);
}
{
void print_binary (int n);
}
------------------------------------------------------------------
thanks in advance
-
That is essentially nothing. How about you give it a try first?
Tip: You can use
x & 0x1
to get a number with all bits 0 except the least significant one, which is set to the value of the least significant bit of x.
And you can use >> to shift the bits in any number.
-
Use strtol
Code:
#include <stdio.h>
#include <stdlib.h>
void print_binary(char *);
int main(){
char i[10];
memset(i,0x00,sizeof(i));
printf ("Please type in your number\n");
gets(i);
print_binary (i);
}
void print_binary (char * n){
char **ptr;
long result;
result=strtol(n,ptr,2);
printf("%d\n",result);
return;
}
-
Nice, but he should convert an integer to a string, not a string to an integer. And you use the endptr argument wrong...
char *endptr;
long l = strtol(str, &endptr, 2);