Son_Nguyen's blog

By Son_Nguyen, history, 9 years ago, In English

Hello everybody. That is my code to show binary a decimal number. It's right when a>=0 but when a<0 that can't work, infinite loop. And I don't know what wrong in this code. Can you help me to solve? Thank so much!

void bi(int a)
{
        if(a==0)
            return;
        bi(a>>1);
        cout<<(a & (1));
}

//I have a nother code and it's right in both case. However I want to know what happen with this code. Sorry for my bad English

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Shift for negative numbers is arithmetic shift, it means that the MSB is copied on shift right. And that means you will never get to 0 by shifting negative number right.

Add check for negative number to your function.

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Operation (a >> b) is filling highest b bits of a of signed bit a. So for a < 0 signed bit equal 1. It, in particular, mean that -1 >> 1 == -1, because binary representation of " - 1" contains 32 ones.