Binary number conversion

Status
Not open for further replies.

varunme

Advanced Member level 3
Joined
Aug 10, 2011
Messages
741
Helped
17
Reputation
36
Reaction score
17
Trophy points
1,318
Activity points
5,764
How can we take the number of "high"s in a binary number ?

like

0b10100000 -> 2
0b01000101 -> 3
0b01111000 -> 4
 

You need to check every bit, then if bit high, increment counter.
Code:
j=0;
for(i=0 ; i < 8 ; i ++)
     if(((DATA>>i)&1) == 1) j++;
 
Reactions: varunme

    varunme

    Points: 2
    Helpful Answer Positive Rating
srhoar,
Very nice links, I didnt got any links like this before
 

You need to check every bit, then if bit high, increment counter.
Code:
j=0;
for(i=0 ; i < 8 ; i ++)
     if(((DATA>>i)&1) == 1) j++;

what can be the problem with the bel

Code:
void main()
{
         port_B =portb;
         DATA = port_B;
        while (1) {
         if (UART1_Data_Ready()) {
        j=0;
      for(i=0 ; i < 8 ; i ++)
      {
       if(((DATA>>i)&1) == 1) j++;


       }
        m=Int2Str(j);
       UART1_Write(m);



    }

     }

}



used

Code:
        UART1_Write(Lo(J));
       UART1_Write(Hi(J));

too, but no luck
 
Last edited:

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…