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;
}
-
\$\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\$Marc-Andre– Marc-Andre2014年07月23日 16:30:20 +00:00Commented Jul 23, 2014 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;
-
1\$\begingroup\$ mask<<1; will not change mask, you want to use mask<<=1; \$\endgroup\$mch– mch2014年06月05日 12:37:11 +00:00Commented Jun 5, 2014 at 12:37
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;
}