Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9c631a0

Browse files
committed
Issue #23319: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch
written by Matthieu Gautier.
1 parent bb1c079 commit 9c631a0

3 files changed

Lines changed: 32 additions & 0 deletions

File tree

Lib/ctypes/test/test_bitfields.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,5 +259,33 @@ class X(Structure):
259259
x.a = 0xFEDCBA9876543211
260260
self.assertEqual(x.a, 0xFEDCBA9876543211)
261261

262+
@need_symbol('c_uint32')
263+
def test_uint32_swap_little_endian(self):
264+
# Issue #23319
265+
class Little(LittleEndianStructure):
266+
_fields_ = [("a", c_uint32, 24),
267+
("b", c_uint32, 4),
268+
("c", c_uint32, 4)]
269+
b = bytearray(4)
270+
x = Little.from_buffer(b)
271+
x.a = 0xabcdef
272+
x.b = 1
273+
x.c = 2
274+
self.assertEqual(b, b'\xef\xcd\xab\x21')
275+
276+
@need_symbol('c_uint32')
277+
def test_uint32_swap_big_endian(self):
278+
# Issue #23319
279+
class Big(BigEndianStructure):
280+
_fields_ = [("a", c_uint32, 24),
281+
("b", c_uint32, 4),
282+
("c", c_uint32, 4)]
283+
b = bytearray(4)
284+
x = Big.from_buffer(b)
285+
x.a = 0xabcdef
286+
x.b = 1
287+
x.c = 2
288+
self.assertEqual(b, b'\xab\xcd\xef\x12')
289+
262290
if __name__ == "__main__":
263291
unittest.main()

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@ Core and Builtins
6666
Library
6767
-------
6868

69+
- Issue #23319: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch
70+
written by Matthieu Gautier.
71+
6972
- Issue #23254: Document how to close the TCPServer listening socket.
7073
Patch from Martin Panter.
7174

Modules/_ctypes/cfield.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -765,6 +765,7 @@ I_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
765765
if (get_ulong(value, &val) < 0)
766766
return NULL;
767767
memcpy(&field, ptr, sizeof(field));
768+
field = SWAP_INT(field);
768769
field = SET(unsigned int, field, (unsigned int)val, size);
769770
field = SWAP_INT(field);
770771
memcpy(ptr, &field, sizeof(field));

0 commit comments

Comments
 (0)