Monday, 11 March 2013

converting numbers/primes into binary

I want to compare some different number systems together with respect to primes. Wanted to know how to convert to binary. Thought this would be in-built to the computers/language, as all numbers are already stored as binary?

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 first
void 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 reverse
    for (int c = i-1; c >=0 ; c--) {
        printf("%d", binaryArray[c]);
    }
    
}

Worked really well in the end:

Type a starting number: 1
Type an end numbers: 20
1 = 1
2 = 10
3 = 11
4 = 100
5 = 101
6 = 110
7 = 111
8 = 1000
9 = 1001
10 = 1010
11 = 1011
12 = 1100
13 = 1101
14 = 1110
15 = 1111
16 = 10000
17 = 10001
18 = 10010
19 = 10011
20 = 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