Anyway, found this forum with lots of different answers. Smallest answer was:
#include
int
main(
void
) {
int
i, target;
printf
(
"Enter a number: "
);
scanf
(
"%d"
, &target);
for
(i = 32; i--;) {
if
(target & (1 << i))
putc
(
'1'
, stdout);
else
putc
(
'0'
, stdout);
}
return
0;
}
although they suggest altering part of it to
for
(i=(j-1);i >= 0; i--)
/* or 'for(i=j;i--; )' would also work but is a bit too cryptic for me to get my head round */
{
if
(target & (1 << i))
putc
(
'1'
, stdout);
else
putc
(
'0'
, stdout);
}
I shall try this out.
I ended up doing it my own way, mostly so that I could practice programming. I used the divide by 2 way, and if there is remainers then print 1, else print 0:
#define BINARYARRAYSIZE 1000
//converts a number into Binary and prints with greatest bit firstvoid convertAndPrintBinary (int number) {//printf("converting to binary\n");int binaryArray [BINARYARRAYSIZE] = {0};int i = 0;for (int result = number; result > 0; result = result/2) {if (result % 2 == 0 ) {binaryArray[i]=0;//printf("0");} else {binaryArray[i]=1;//printf("1");}i++;}//printf("%d\n", i );//prints out array in reversefor (int c = i-1; c >=0 ; c--) {printf("%d", binaryArray[c]);}}
Worked really well in the end:
Type a starting number: 1Type an end numbers: 201 = 12 = 103 = 114 = 1005 = 1016 = 1107 = 1118 = 10009 = 100110 = 101011 = 101112 = 110013 = 110114 = 111015 = 111116 = 1000017 = 1000118 = 1001019 = 1001120 = 10100
I used BINARYARRAYSIZE because I didn't want to run the first for loop twice; once to measure how big the array needed to be, and the second to fill it. When I didn't give the array a size to begin with, it kept erroring. But 1000 digits for binary is a large number!
No comments:
Post a Comment