Skip to content

Commit 9472907

Browse files
committed
py: Fix handling of negative numbers in struct.pack of q/Q.
1 parent ae2c81f commit 9472907

2 files changed

Lines changed: 6 additions & 2 deletions

File tree

py/binary.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,10 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte **
291291
#endif
292292
{
293293
val = mp_obj_get_int(val_in);
294+
// sign extend if needed
295+
if (BYTES_PER_WORD < 8 && size > sizeof(val) && is_signed(val_type) && (mp_int_t)val < 0) {
296+
memset(p + sizeof(val), 0xff, size - sizeof(val));
297+
}
294298
}
295299
}
296300

py/mpz.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1441,8 +1441,8 @@ void mpz_as_bytes(const mpz_t *z, bool big_endian, mp_uint_t len, byte *buf) {
14411441
for (; bits >= 8; bits -= 8, d >>= 8) {
14421442
mpz_dig_t val = d;
14431443
if (z->neg) {
1444-
d = (~d & 0xff) + carry;
1445-
carry = d >> 8;
1444+
val = (~val & 0xff) + carry;
1445+
carry = val >> 8;
14461446
}
14471447
if (big_endian) {
14481448
*--b = val;

0 commit comments

Comments
 (0)