Search code examples
c++avr

AVR C++ uint32_t weird behaviour


uint32_t a = 65536;
uint32_t b = 1 << 16;

Why is a != b here, but

uint32_t a = 65536;
uint32_t b = 65536;

here a == b although it should technically be the same?

I'm using CLion as an IDE and CMake 3.7.1 with Arduino CMake.


Solution

  • uint32_t b = 1 << 16;
    

    as you noticed, this breaks down if you don't cast 1 to a 32-bit integer first:

    The literal 1 is the default integer type on your compiler. Don't know which, but it's either an 8 or a 16 bit int.

    Now, assume it's an 16 bit in. When you shift 1 left 16 times, you just... well, it doesn't make sense. So, make your 1 a 32 bit int first, then shift.