I have a simple program. Notice that I use an unsigned fixed-width integer 1 byte in size.
#include
#include
Look into two's complement and how computer stores negative integers.
Try this
#include
#include
#include
int main()
{
uint8_t x = 1;
int shiftby=0;
shiftby=8*sizeof(int)-1;
std::cout << (x << shiftby) << '\n'; // or std::cout << (x << 31) << '\n';
std::cout << ~x;
std::cin.clear();
std::cin.ignore(std::numeric_limits::max(), '\n');
std::cin.get();
return 0;
}
The output is -2147483648
In general if the first bit of a signed number is 1 it is considered negative. when you take a large number and shift it. If you shift it so that the first bit is 1 it will be negative
** EDIT **
Well I can think of a reason why shift operators would use unsigned int. Consider right shift operation >>
if you right shift -12 you will get 122 instead of -6. This is because it adds a zero in the beginning without considering the sign