Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVR C++ uint32_t weird behaviour

Tags:

c++

avr

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.

like image 461
aquaatic Avatar asked Mar 09 '23 10:03

aquaatic


1 Answers

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.

like image 156
Marcus Müller Avatar answered Mar 20 '23 13:03

Marcus Müller