//* Signed vs. Unsigned variables, some binary operations and bit shifting *

#include <iostream> #include <iomanip> using namespace std; int main() { cout << "Please enter four numbers 0..255: "; unsigned char bytes[4]; for(int i=0; i<4; i++) { short int input; cin >> input; bytes[i]=(unsigned char)input; } signed char chars[4]; // this "singed char" is the default "char" for(int i=0; i<4; i++) { chars[i]=bytes[i]; } unsigned long int result1; result1 = bytes[0]; result1 = (result1<<8) | bytes[1]; // result1 = result1*256 + bytes[1] result1 = (result1<<8) | bytes[2]; result1 = (result1<<8) | bytes[3]; unsigned long int result2; result2 = chars[0]; result2 = (result2<<8) | chars[1]; result2 = (result2<<8) | chars[2]; result2 = (result2<<8) | chars[3]; unsigned long int result3; result3 = 0xFF & chars[0]; result3 = (result3<<8 ) | (0xFF & chars[1]); result3 = (result3<<8 ) | (0xFF & chars[2]); result3 = (result3<<8 ) | (0xFF & chars[3]); signed long int result4; // this is the default "long int" result4=(signed long int)result1; cout << "Bytes read: "; for(int i=0; i<4; i++) cout << setw(5) << (int)bytes[i]; cout << endl; cout << "Chars read: "; for(int i=0; i<4; i++) cout << setw(5) << (int)chars[i]; cout << endl; cout << "unsigned bytes in unsigned accumulation: " << setw(15) << result1 << endl; cout << "signed bytes in unsigned errorous: " << setw(15) << result2 << endl; cout << "signed bytes in unsigned accumulation: " << setw(15) << result3 << endl; cout << "unsigned bytes in signed accumulation: " << setw(15) << result4 << endl; return(0); }