Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I wrote a program to display data in memory as binary and it worked. (It gave me immense sense of satisfaction and joy to see this work. I guess this happens to newbies who are just testing the waters). I know this isn't some terribly smart code, and I'm sure there must be surely lots of better ways to do this. Any advice and help would be great. If I've done something wrong in this program or if there is any bad programming practice, I would be happy to be corrected.

#include<stdio.h>

int main()
{

  char mychar = 'a';
  int count = 0;
  int bitmask = 128;
  while (count < 8){

    if (mychar &  bitmask){
      printf("1");
    }
    else{
       printf("0");
    }

    bitmask = bitmask / 2;
    count = count +1;
  }

return 0;

}
share|improve this question

migrated from stackoverflow.com Jul 23 '14 at 11:34

This question came from our site for professional and enthusiast programmers.

    
I guess this happens to newbies who are just testing the waters - I can assure you I'm still proud when what I just code is working. It's a feeling I don't want to lose since it's what make the job fun, overcoming problem and find a solution that work. –  Marc-Andre Jul 23 '14 at 16:30

2 Answers 2

You may use the shift operation;

char mask = 0x01; //define initial mask

if (mask&mychar) printf("1"); // check that spesific bit

mask<<=1; //shift left

of course if you want to start checking from right hand then shift right you can do :

char mask = 0x80;

mask>>=1;
share|improve this answer
1  
mask<<1; will not change mask, you want to use mask<<=1; –  mch Jun 5 '14 at 12:37
    
Thank's @Manül you are definitely right –  chouaib Jun 5 '14 at 23:55

Welcome to C, your program seems ok.

Any advices and help would be great. If I 've done something wrong in this program or if there is any bad programming practice

There is no need to call printf on each iteration, store it in a buffer (using malloc or a static string). And a good practice is to reuse code (using functions):

#include <stdio.h>
#include <limits.h>

static char *sbin(unsigned long v, int len)
{
    static char s[sizeof(v) * CHAR_BIT + 1];
    int i, j;

    for (i = len - 1, j = 0; i >= 0; i--, j++) {
        s[j] = (v & (1UL << i)) ? '1' : '0';
    }
    s[j] = 0;
    return s;
}

int main(void)
{
    printf("%s\n", sbin('a', 8));
    return 0;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.