Negative integer bitswitching

I'm wondering why does the following code loops infinitely :

1
2
3
4
5
int temp = -4;
	while (temp)
	{
		temp >>= 1;
	}


As I understand it, this loop should go through all 32 bits that an integer consists of and then exit, but that seems not to be the case. Why ?

I get it that ints are stored in U2 system, but that shouldn't prevent me from switching through all the bits leaving only zeros.

Your system is doing an arithmetic shift, and not a logical shift. This is typical of signed integers, as it more closely simulates a divide-by-2 operation and is much more useful in practice.

A logical shift right uses 0 as input for the shifted in high bit.
An arithmetic shift right uses the value of the current high bit for the shifted in high bit.

IE:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
8-bit signed:    11100101

>> 1 logical:    01110010
>> 1 arithmetic  11110010


For arithmetic:  11100101
                 v
                 |
                 this bit used to shift in
                 |
              +--+
              |
              +->11110010
Last edited on
Topic archived. No new replies allowed.