AdamTopi
AdamTopi

Reputation: 63

Converting int to binary, using an array of char to represent it

Working on a homework assignment for class, part of the assignment has us converting from base ten to binary, and representing the binary number as an array of type char. For some reason it's not computing the right most bit. Any help would be appreciated.

#include <stdlib.h>
#include <stdio.h>
xtractmsg(int a)
{
   int rem,i,b,j,quotient;
   char binaryNumber[16];



   for(i = 0; i <= 16; i++){

        if(a == 0)
           binaryNumber[i]='0';
        else{

           rem = a % 2;

           if(rem == 0)
                   binaryNumber[i]='1';
           else
                  binaryNumber[i]='0';
          a=a/2;
        }


   }

    for(j=15; j>=0;j--)
        printf("%c,%d",binaryNumber[j]);


}

input is ten, output is 0000000000000101.

Upvotes: 2

Views: 2940

Answers (2)

suspectus
suspectus

Reputation: 17258

Two things here need addressing.

The loop condition is wrong by one-:

for(i = 0; i < 16; i++) {

The logic needs reversing-:

if(rem == 0)
    binaryNumber[i]='0';
else
    binaryNumber[i]='1';

Upvotes: 0

Andrey
Andrey

Reputation: 60065

I will not give you direct answer, because it is homework, I will point where to search for. Take a close look at what you do after you get a remainder. Try to print it right where you get it and analyze what you see.

Unrelated but also wrong for(i = 0; i <= 16; i++), will eventually write to 17th element, which is nonexistent.

Upvotes: 2

Related Questions