/* Am not able to understand the operation happening in function showbits(), please help*/
#include <stdio.h>
void showbits (unsigned char);
int main()
{
unsigned char num=225,j,k;
printf(\nDecimal %d is same as binary", num);
showbits (num);
for(j=0; j<=4; j++)
{
k=num<<j;
printf (\n%d left shift %d gives", num, j);
showbits(k);
}
return 0;
}
void showbits (unsigned char n)
{
int i;
unsigned char j,k, andmask;
for(i=7; i>=o; i--)
{
j=i;
andmask = 1 << j;
k = n & andmask; /* what happens during this instruction */
k == 0 ? printf("0") : printf("!"); /*and here too, pls help.*/
}
}
surfingturtle
0
Light Poster
Recommended Answers
Jump to Post
k = n & andmask;
The bitwise AND will set each corresponding bit to 1 if the same bit in both arguments is 1. Otherwise the bit will be set …
Jump to PostThe second time in the loop, j will be 6, so left shifting 1 results in 01000000, wich now will be andmask, so again 1 wil be printed.
When j becomes 4 down to 1 a 0 will be printed, the last time, when j=0, a 1 will be printed, …
Jump to PostYou have quite a few errors in your code.
Line 16 needs a "
Line 27 replace o with 0
Line 32 replace ! with 1To see what's going on use a few temporary test prints.
All 9 Replies
deceptikon
1,790
Code Sniper
Team Colleague
Featured Poster
surfingturtle
0
Light Poster
ddanbe
2,724
Professional Procrastinator
Featured Poster
surfingturtle
0
Light Poster
ddanbe
2,724
Professional Procrastinator
Featured Poster
vegaseat
1,735
DaniWeb's Hypocrite
Team Colleague
surfingturtle
0
Light Poster
ddanbe
2,724
Professional Procrastinator
Featured Poster
surfingturtle
0
Light Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.