### Thread: Arithmetic or logical right shift - buggy program!

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Apr 2012
Posts
28
Rep Power
0

#### Arithmetic or logical right shift - buggy program!

Trying to write a program to determine whether or not my computer performs an arithmetic or logical right shift. (This is an exercise from Programming in C).

Whenever I run the following program, it outputs -1 twice, so there's no difference to the variable after performing the right shift(?).

Can anybody tell me where I'm going wrong? Help is much appreciated! :)

Code:
```// Program to determine whether this particular computer performs
// an arithmetic or logical right shift
//
// This can only be determined by right shifting a signed value,
// so we need to right shift a signed int

#include <stdio.h>

int main (void)
{
// define a negative signed int with value -1
//  in binary (32 bits) this will be:
// 1000 0000 0000 0000 0000 0000 0000 0001
int test_int = -1;
printf("At beginning of program, test_int = %d\n\n", test_int);

// right shift the negative signed int by one place
// so now, if the computer performs arithmetic right shift,
// a 1 will be shifted in on the left hand side, and it becomes:
// 1100 0000 0000 0000 0000 0000 0000 0000
// this is a negative number

// if the computer performs logical right shift,
// a 0 will be shifted in on the left hand side, and it becomes:
// 0100 0000 0000 0000 0000 0000 0000 0000
// this is a positive number

test_int  = test_int >> 3; // right shift the bits three places

// if test here on result of right shift
// this will tell us whether the computer performs arithmetic or
// logical right shift
if (test_int < 0) // arithmetic right shift
{
printf("test_int = %d\n", test_int);
printf("Therefore this computer performs arithmetic right shift.");
}

if (test_int > 0) // logical right shift
{
printf("test_int = %d\n", test_int);
printf("Therefore this computer performs logical right shift.");
}

return 0;
}```
2. > Whenever I run the following program, it outputs -1 twice, so there's no difference to the variable after performing the right shift(?).
-1 in 2's complement is all bits set (1111 1111 ....)
So right-shifting it and inserting 1's to the left isn't going to change that.