Skip to content

Can't convert -0x80000000 to int32 with mp_obj_int_get_checked #2868

Description

@ghseb

Hello,

correct me if im wrong, but

mp_int_t in = -0x80000000;
mp_obj_t i = mp_obj_new_int_from_ll(in);
mp_int_t out = mp_obj_int_get_checked(i);

throws

OverflowError: overflow converting long int to machine word

I would expect this conversion to be valid since -0x80000000 is in the range of a int32.

This works:

mp_int_t in = -0x7FFFFFFF;
mp_obj_t i = mp_obj_new_int_from_ll(in);
mp_int_t out = mp_obj_int_get_checked(i);

Sebastian

Activity

  1. changed the title [-]Possible [/-] [+]Invalid conversion to int32 in mp_obj_int_get_checked[/+] on Feb 13, 2017
  2. dpgeorge commented on Feb 14, 2017

    @dpgeorge
    Member

    This is an artefact of how mpz's (bignums) are converted to C-level ints: the conversion is done using positive numbers, and then only at the end is is made negative if the mpz's negative flag is set. The overflow is checked during the conversion to a positive number, and since 0x80000000 is too large for a signed 32-bit int, it exits with an overflow.

    You could try using mp_obj_int_get_truncated instead.

  3. Jongy commented on Jul 17, 2019

    @Jongy
    Contributor

    You could try using mp_obj_int_get_truncated instead.

    Cool! This works nicely.

    Anyway, I found this issue while looking around with the exact same problem.

    @dpgeorge :
    How about we document mp_obj_int_get_truncated so others know it can be used this way? Perhaps even create a nice wrapper mp_obj_int_get_uint?

    Actually I see there's a mpz_as_uint_checked, only that it's unused. So I'll create a PR with mp_obj_int_get_uint_checked.

  4. added a commit that references this issue on May 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions