Thursday, 10 July 2014

Logical Vs Arithmatic Shift in C++

Code:

#include <iostream>
using namespace std;

void print_binary_representation(unsigned int x)
{
    size_t siz = 8*sizeof(x);    // sizeof returns size in bytes.
    for (size_t i = siz; i>0; i--)
    {
        int val = (((x >> (i-1)) << (siz-1)) >> (siz-1));
        cout << val;
    }
    cout << endl;
}

int main()
{
    int i = 5;
    unsigned int ui = 10;
    int ni = -10;
    
    int i_shifted = (i >> 1);
    unsigned int ui_shifted = (ui >> 1);
    int ni_shifted = (ni >> 1);
    unsigned int uni = (unsigned int)ni;
    int iuni_shifted =  (int)(((unsigned int)ni) >> 1);
    
    cout << 1 << ": "; print_binary_representation(1);
    cout << 0 << ": "; print_binary_representation(0);
    cout << -1 << ": "; print_binary_representation(-1);
    cout << "5 shifted: " << i_shifted << ": "; print_binary_representation(i_shifted);
    cout << "10 shifted: " << ui_shifted << ": "; print_binary_representation(ui_shifted);
    cout  << "-10 shifted: " << ni_shifted << ": "; print_binary_representation(ni_shifted);
    cout  << "(unsigned int)-10 shifted: " << uni << ": "; print_binary_representation(uni);
    cout << iuni_shifted << ": "; print_binary_representation(iuni_shifted);
    
    return 0;
}



Output:

1: 00000000000000000000000000000001

0: 00000000000000000000000000000000

-1: 11111111111111111111111111111111

5 shifted: 2: 00000000000000000000000000000010

10 shifted: 5: 00000000000000000000000000000101

-10 shifted: -5: 11111111111111111111111111111011

(unsigned int)-10 shifted: 4294967286: 11111111111111111111111111110110

2147483643: 01111111111111111111111111111011



Using Visual Studio 2012 64-bit compiler.

No comments: