Shifting right one positon is often used to divide a number by two. That is why when shifting right negative numbers the MSB is filled with 1 to get the right result. Alwais thought that this is what should happen with standard conforming compilers but hammer pointed out that this is implementation-defined.
Try this:
Code:
#include <iostream>
#include <iomanip>
using namespace std;
string byte_to_bin(unsigned char c) {
unsigned char mask = 0x80;
string ret;
for ( int i = 0; i < 8; ++i ) {
ret += ( c & mask ? "1": "0"); mask >>= 1;
}
return ret;
}
int main() {
char c = -118;
cout << setw(4) << (int)c << " ( " << byte_to_bin(c) <<" ) >> 1 = ";
c >>= 1;
cout << setw(4) << (int)c << " (" << byte_to_bin(c) << ")" << endl;
c = 62;
cout << setw(4) << (int)c << " ( " << byte_to_bin(c) <<" ) >> 1 = ";
c >>= 1;
cout << setw(4) << (int)c << " (" << byte_to_bin(c) << ")" << endl;
}
I get this output with g++
Code:
-118 ( 10001010 ) >> 1 = -59 (11000101)
62 ( 00111110 ) >> 1 = 31 (00011111)
Kurt
edit: sorry that I posted C++ code in the C-Forum