2
\$\begingroup\$

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;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 5, 2014 at 7:28
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Jul 23, 2014 at 16:30

2 Answers 2

1
\$\begingroup\$

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;
answered Jun 5, 2014 at 7:38
\$\endgroup\$
1
  • 1
    \$\begingroup\$ mask<<1; will not change mask, you want to use mask<<=1; \$\endgroup\$ Commented Jun 5, 2014 at 12:37
1
\$\begingroup\$

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;
}
answered Jun 5, 2014 at 7:45
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.