-1
int main()
{
    unsigned n;
    cin>>n;
    for(int i=(1<<31);i>0;i/=2)
        (i&n)?(cout<<1):(cout<<0);
}

I ran the following code with n=1 but it prints nothing on the console. Changing the type of variable i to unsigned did the trick and printed 00000000000000000000000000000001. Any idea why?

LPs
  • 16,045
  • 8
  • 30
  • 61
  • 1
    What is the number `0x80000000` of a signed 32 bit variable....? – LPs Jun 07 '17 at 07:42
  • And what is the end condition of the loop...? – stefaanv Jun 07 '17 at 07:43
  • 2
    [`i /= 2` and `i >>= 1` are not the same](https://stackoverflow.com/q/10681375/995714) – phuclv Jun 07 '17 at 07:44
  • Use `unsigned int i`. – Jarod42 Jun 07 '17 at 07:46
  • As a side note: using ternary operator (?:) with statements seems weird. It is more meant for expressions: `x = cond ? expr1: expr2;` so in your case `std::cout << (i&n? 1: 0);` or even better without the ternary operator: `std::cout << (i&n != 0);` – stefaanv Jun 07 '17 at 09:36

2 Answers2

3

Assuming two's complement, 1 << 31 results in a negative value, so your test for i > 0 fails immediately with the first test. You most likely would have had more luck with i != 0 then.

But we aware that 1 << 31 is a signed integer overflow, which is undefined behaviour anyway! So you should do 1U << 31 instead, too. If you assign this then positive value to a signed int, which is not capable to hold it, you have again undefined behaviour. So the correct for loop would look like this:

for(unsigned int i = 1U << 31; i > 0; i /= 2)

Although i /= 2 for unsigned values is equivalent to a bitshift (and is likely to be compiled to), I would prefere the bitshift operation explicitly here (i >>= 1), as this is what you actually intend.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
  • Ahh I see.. Thanks a lot.. I did not notice the sign condition I myself put on my loop.. Thanks for pointing out the overflow bit! Will use `1U << 31` – Aneesh Bose Jun 07 '17 at 08:47
2

Given that your platform is a 32-bit one, int i with a value of (i<<31) is a negative number. So, the execution never enters for-loop because you want i>0.

awakened
  • 192
  • 9