Блог пользователя Son_Nguyen

Автор Son_Nguyen, история, 9 лет назад, По-английски

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

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
9 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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.