bit operations

Hi - can anyone explain to me why these are not equivical?
Or at least they are not on my iMac...

Thanks in advance

James

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <bitset>

int main() {
   
    // The  bitwise shift operations
    
    unsigned short number{16387};
    
    
    auto result{static_cast<unsigned short>(number << 2)}; //shift left 2 bit positions and store in result
    
    std::cout << std::bitset<20>(number) << " number:- " << number << std::endl;
    std::cout << std::bitset<20>(result) << " left 2 bit positions:- " << result << std::endl;
    
    result = static_cast<unsigned short>(number >> 2);
    std::cout << std::bitset<20>(result) << " right 2 bit positions:- " << result << std::endl;
    
    std::cout << "\n" << std::endl;
    
    
    
    unsigned short another_number{16387};
    std::cout << std::bitset<20>(another_number) << " " << another_number<< std::endl;
    
    auto shifted{static_cast<unsigned short>(another_number <<= 2)};
    std::cout << std::bitset<20>(shifted) << " " << shifted << std::endl;
    
    shifted = static_cast<unsigned short>(another_number >>= 2);
    std::cout << std::bitset<20>(shifted) << " " << shifted << std::endl;
    
    
    return 0;
}
Last edited on
The difference is because you use << and >> in the upper code and <<= and >>= in the lower code.
Sorry! A silly moment, I have finally worked it out. The penny has drppped so to speak.
Thanks for your help.

James
Strange example, since 16387 << 2 comes out to 65548, and typical range of a 2-byte unsigned short is from 0 to 65535. "result" in the first section is likely a 4-byte int holding 65548. In the second case, another_number would try to store this value to itself, wrap around and end up storing 12.

This is just an observation of a logical error in the making, in addition to the other issue.

Last edited on
Topic archived. No new replies allowed.