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

Skip to content

Commit f9e91c9

Browse files
committed
Given that ord() of a bytes object of length 1 is defined, it should
never return a negative number.
1 parent 2b08b38 commit f9e91c9

3 files changed

Lines changed: 15 additions & 1 deletion

File tree

Lib/test/test_builtin.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1383,6 +1383,15 @@ def test_ord(self):
13831383
self.assertEqual(ord(' '), 32)
13841384
self.assertEqual(ord('A'), 65)
13851385
self.assertEqual(ord('a'), 97)
1386+
self.assertEqual(ord('\x80'), 128)
1387+
self.assertEqual(ord('\xff'), 255)
1388+
1389+
self.assertEqual(ord(b' '), 32)
1390+
self.assertEqual(ord(b'A'), 65)
1391+
self.assertEqual(ord(b'a'), 97)
1392+
self.assertEqual(ord(b'\x80'), 128)
1393+
self.assertEqual(ord(b'\xff'), 255)
1394+
13861395
if have_unicode:
13871396
self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
13881397
self.assertRaises(TypeError, ord, 42)

Lib/test/test_bytes.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,11 @@ def test_rstrip(self):
671671
self.assertEqual(b.rstrip(b'im'), b'mississipp')
672672
self.assertEqual(b.rstrip(b'pim'), b'mississ')
673673

674+
def test_ord(self):
675+
b = b'\0A\x7f\x80\xff'
676+
self.assertEqual([ord(b[i:i+1]) for i in range(len(b))],
677+
[0, 65, 127, 128, 255])
678+
674679
# Optimizations:
675680
# __iter__? (optimization)
676681
# __reversed__? (optimization)

Python/bltinmodule.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1482,7 +1482,7 @@ builtin_ord(PyObject *self, PyObject* obj)
14821482
/* XXX Hopefully this is temporary */
14831483
size = PyBytes_GET_SIZE(obj);
14841484
if (size == 1) {
1485-
ord = (long)*PyBytes_AS_STRING(obj);
1485+
ord = (long)((unsigned char)*PyBytes_AS_STRING(obj));
14861486
return PyInt_FromLong(ord);
14871487
}
14881488
}

0 commit comments

Comments
 (0)