简体   繁体   中英

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?

Why does the program output 24 ?

You are right, 12 is 0b1100 in its binary representation. That being said, it also is 0b001100 if you want. In this case, bitshifting to the left gives you 0b011000 , which is 24 . The program produces the excepted result.

Where does this stop?

You are using an int variable. Its size is typically 4 bytes (32 bits) when targeting 32-bit. However, it is a bad idea to rely on int 's size. Use stdint.h when you need specific sizes variables.

A word of warning for bitshifting over signed types

Using the << bitshift operator over negative values is undefined behavior. >> 's behaviour over negative values is implementation-defined. In your case, I would recommend you to use an unsigned int (or just unsigned which is the same), because int is signed.

How to get the result you except?

If you know the size (in bits) of the number the user inputs, you can use a bitmask using the & (bitwise AND) operator. eg

result = (number << 1) & 0b1111; // 0xF would also do the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM