Skip to content

Division error when mixing (int32_t) with (uint32_t) #11419

Closed
@Rob58329

Description

@Rob58329

Board

Waveshare ESP32-S3 zero

Device Description

Plain board only.

Hardware Configuration

Plain board only.

Version

github.com/espressif/arduino-esp32 as at 31May25

IDE Name

Adruino IDE v1.8.19

Operating System

Windows 10

Flash frequency

80MHz

PSRAM enabled

no

Upload speed

921600

Description

The following sketch/calculation gives a big (int32_t) number when it should give a small negative (int32_t) number.

A similar error occurs if doing a (uint32_t) divided by an (int32_t).

This error can be got around by limiting the (uint32_t) number to 0x7FFFFFFF and then casting it to an (int32_t).

However, I think it would be preferable if this was not necessary!?!

Sketch

void setup() {
  Serial.begin(115200);
  delay(3000);
  int32_t  x=-2000;
  uint32_t y= 1000;
  int32_t  z=x/y; // an (int32_t) divided by a (uint32_t)
  Serial.printf("Error: x=%li, y=%lu, x/y=z=%li\n",x,y,z); // Error: x=-2000, y=1000, x/y=z=4294965
  x=abs(x); z=x/y;
  Serial.printf("But:   x=%li, y=%lu, x/y=z=%li\n",x,y,z); // But:   x=2000, y=1000, x/y=z=2
}

void loop() {}

Debug Message

Error: x=-2000, y=1000, x/y=z=4294965
But:   x=2000, y=1000, x/y=z=2

Other Steps to Reproduce

None

I have checked existing issues, online documentation and the Troubleshooting Guide

  • I confirm I have checked existing issues, online documentation and Troubleshooting guide.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions