Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Program explanation needed (decimal to binary conversion)

Status
Not open for further replies.

azarutz

Member level 2
Member level 2
Joined
Mar 4, 2012
Messages
42
Helped
1
Reputation
2
Reaction score
1
Trophy points
1,288
Location
India
Activity points
1,579
Hi ,this is a part of decimal to binary conversion program and i can't understand the statement inside for loop some body explain me .

Code:
for (c = 31; c >= 0; c--)
  {
   [COLOR="#FF0000"] k = n >> c[/COLOR];
 
    if (k & 1)
      printf("1");
    else
      printf("0");
  }

this is 32-bit binary output program . so c initialized to 31 .
 

k = n >> c means take value in n and bit shift it to right c times store value in k.
if(k & 1) means if k bit 0 is set print 1 else print 0. (& is and operation)

Lets say n has decimal value 5. In binary "00000000000000000000000000000101"

first round:
c=31
k=0. In binary "00000000000000000000000000000000" (n shifted 31 times. zeros filled from left)
k & 1 = 0 print 0
second round:
c=30
k=0. In binary "00000000000000000000000000000000" (n shifted 30 times. zeros filled from left)
k & 1 = 0 print 0
...
c count down in loop.
when
c=2
k=1. In binary "00000000000000000000000000000001" (n shifted 2 times. zeros filled from left)
k & 1 = 1 print 1

c=1
k=2. In binary "00000000000000000000000000000010" (n shifted 1 times. zeros filled from left)
k & 1 = 0 print 0

c=0
k=5. In binary "00000000000000000000000000000101" (n shifted 0 times.)
k & 1 = 1 print 1
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top