arduino / Arduino

Arduino IDE 1.x
https://www.arduino.cc/en/software
Other
14.18k stars 7.01k forks source link

~ operator always expands to 32bit on 8bit avr #11964

Closed PeterW-avr closed 4 months ago

PeterW-avr commented 4 months ago

Arduino 1.8.19 contains avr-gcc 7.3.0: The bitwise inversion operator ~ disregards the type of the operand and always expands the result to 32 (!) bits. Problably this only appers in conjunction with Serial.println().

Example:

 ~0  = 0xFFFFFFFF
 ~PIND = 0xFFFFFFxx
 ~(uint8_t)PIND = 0xFFFFFFxx

Serial.println(~0,HEX); FFFFFFFF

PeterW-avr commented 4 months ago

In conjunction with >> the value is expanded to 16 bits internally, then inverted, finally shifted right. This behaviour will give an incorrect result.

~(uint8_t)PIND >> 4 = 0xF#

    in r24,9
    ldi r25,0 <---- unexpected expansion to 16 bit value 0x00##
    com r24
    com r25 <---- unexpected inversion of zero, gives 0xFF##
    ldi r18,4
    1:
    asr r25 <---- unexpected insertion of bits from high byte
    ror r24
    dec r18
    brne 1b
    sts val,r24 <---- result: high nibble is all set, value is 0xF# rather than 0x0#
per1234 commented 4 months ago

Hi @PeterW-avr. This repository contains the code base for the retired Arduino IDE 1.x application.

Reports of problems with avr-gcc are off topic here. You must report any problems with avr-gcc to the maintainers of that project (after verifying it still occurs with the latest version).

Arduino does not maintain or participate in the development of avr-gcc in any way so we are not able to do anything about this report.