Ali Almis Ali Almis - 2 months ago 6
C++ Question

shifting the binary numbers in c++

#include <iostream>

int main()
{
using namespace std;

int number, result;

cout << "Enter a number: ";
cin >> number;
result = number << 1;
cout << "Result after bitshifting: " << result << endl;
}


If the user inputs
12
, the program outputs
24
.

In a binary representation,
12
is
0b1100
. However, the result the program prints is
24
in decimal, not
8
(
0b1000
).

Why does this happen? How may I get the result I except?

Answer

You are doing a bit shift. Keep in mind that 1100 is 000...01100 (usually 32 bits for integer). then:

0000000000001100
0000000000011000
0000000000110000

and so on, but the computer doesn't print the zeros in the beginning if you try to convert it to binary.

That is why your code will output 24 and not 8. See on ideone.com

If you want to limit your number to 4 bits, use the & (bitwise and) operator: number & 16, that will bring only the most right 4 bits, and so:

0001100 (12)dec << 1 = 
0011000 (24)dec & 16 =
0001000 (08)dec
Comments