2

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.

3
  • 1
    compile with maximal warnings turned on, that should tell you something about your printf call. Commented Mar 19, 2013 at 22:27
  • The error is very small. You've got most of it right. Commented Mar 19, 2013 at 22:34
  • yeah I deleted the extra %d, it was originally there to help me debug something else. Thanks Commented Mar 19, 2013 at 22:43

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ah, I had my assignments reversed. Thank you so much!
@AdamTopi actually you shot your own foot, this condition if(a == 0) is completely unnecessary, 0 % 0 == 0, so if it was not there you would notice that everything is just inverted. Try to write minimal but sufficient code, more code you have, more likely you have a bug.
0

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.