Skip to content

Wrap Python's ~ on unsigned and << on fixed-width integers to the C family's width [patch] - #358

Merged
matt-edmondson merged 1 commit into
mainfrom
fix/351-python-fixed-width-bitwise
Nov 4, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
fix/351-python-fixed-width-bitwise

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #351

What changed

Python integers are unbounded, so the generated Python gave different answers from every other target. ~x on a uint came out as -6 where the others give 4294967290, and 1 << 31 on an int came out as 2147483648 where they give -2147483648. This ports the JavaScript fix from #256 / PR #322 to PythonGenerator, keyed on static type the same way:

  • ~ on uint / ulong is masked to the width: ((~x) & 0xFFFFFFFF) / & 0xFFFFFFFFFFFFFFFF. ~ on int / long already matches two's complement, so it is unchanged.
  • << on uint / ulong, keyed on the left operand, is masked the same way.
  • << on int / long is wrapped back into the signed range: ((((x << n) + 0x80000000) & 0xFFFFFFFF) - 0x80000000), using the 64-bit constants for long.
  • <<= on those types is written out as x = <wrapped shift>, the same way /= and %= already are.

As the issue asked, this covers only the bitwise and shift operators. >>, &, | and ^ already give the C family's result on in-range operands, and operands of unknown type are left as they were.

Tests

In WideIntegerBitwiseOperatorTests:

With the generator change stashed, Python_FixedWidthBitwiseOperators_MatchCSharp fails, and it passes with the change. Full Coder.Test suite: 1553 passed, 0 failed.


Generated by Claude Code

…amily's width [patch]

Python integers are unbounded, so ~x on a uint or ulong was negative and x << n on an int,
uint, long or ulong never wrapped, disagreeing with every other target. ~ on uint/ulong is now
masked to its width, << on the four fixed-width types (and <<=) is masked or wrapped back into
the signed range, keyed on the left operand's static type. ~ on signed integers already
matched two's complement and is unchanged.

Fixes #351

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017vfJW6NRQ27ovPhjARcxRW
@sonarqubecloud

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit 0f79e0b into main Nov 4, 2026
16 checks passed
@matt-edmondson
matt-edmondson deleted the fix/351-python-fixed-width-bitwise branch November 4, 2026 00:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Python output gives a negative result for ~ on uint/ulong and never wraps <<, disagreeing with every other target

1 participant