arduino-unoarduino-c++avr-gcc

Arduino Nano ATmega328P C++; unsigned 8bit shift right generates 16bit code. This wastes time and memory. Can this be fixed or avoided?


With an Arduino Nano ATmega328P (Arduino IDE 1.8), the following C++ code (with 8bit operands):

  volatile uint8_t un8 = 123;
  volatile uint8_t res8;
  res8 = un8 >> 1;

generates a 16bit shift (via avr-gcc (GCC) 5.4.0)

  volatile uint8_t un8 = 123;
 218:   ba 82           std Y+2, r11    ; 0x02
../StrangeShiftRightCode/StrangeShiftRightCode.ino:21
  volatile uint8_t res8;
  res8 = un8 >> 1;
 21a:   8a 81           ldd r24, Y+2    ; 0x02
 21c:   90 e0           ldi r25, 0x00   ; 0
 21e:   95 95           asr r25
 220:   87 95           ror r24
 222:   89 83           std Y+1, r24    ; 0x01

which seems to waste both time and space. Can this be fixed? Or is there some option to be less wasteful?


Solution

  • Yes, it has been fixed. But Ubuntu 20.04 doesn't 'see' anything modern enough to download/update.

    Ironically, with the [faulty] compiler I'm using,

     my_uint8_t / 2
    

    generates the code I want (single 8-bit shift),

    Whilst my "better than dividing by 2 code" I used back in the 80's,

     my_uint8_t >> 1
    

    generates more (and unnecessary) assembler code.