Title: Specification of bitshift on integers should clearly state floor division used
Type: enhancement Stage: needs patch
Components: Documentation Versions: Python 3.9, Python 3.8, Python 3.7
Status: open Resolution:
Dependencies: Superseder:
Assigned To: docs@python Nosy List: docs@python, mark.dickinson, ncoghlan
Priority: normal Keywords:

Created on 2020-01-11 06:59 by ncoghlan, last changed 2020-01-12 05:12 by ncoghlan.

Messages (3)
msg359786 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2020-01-11 06:59
While reviewing ISO-IECJTC1-SC22-WG23's latest draft of their Python security annex, I noticed that doesn't explicitly state that *floor* division is used for right shift operations, so right-shifting a negative number by more bits than it contains gives -1 rather than 0.

This is consistent with the way the language spec defines both binary right-shifts (as division by "pow(2, n)" and floor division (as rounding towards negative infinity), so this is just a documentation issue to note that we should make it clearer that this behaviour is intentional.
msg359817 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2020-01-11 19:10
Is the fix as simple as adding the word "floor" before "division" in the "equivalent to division by [...]" phrase?

> A right shift by n bits is equivalent to floor division by pow(2, n) without overflow check. 

This text was probably written before // was introduced; maybe we can rewrite in terms of //? "x >> n" should be identical to "x // pow(2, n)" for any nonnegative "n".

I confess that I've no idea what the "without overflow check" bit means, but I suspect it's no longer relevant post int/long-unification.
msg359832 - (view) Author: Nick Coghlan (ncoghlan) * (Python committer) Date: 2020-01-12 05:12
Aye, adding "floor" to the existing footnote would be the minimal fix. I'm just wondering whether it's also worth stating that this means that positive integers saturate at zero, while negative integers saturate at -1.
Date User Action Args
2020-01-12 05:12:25ncoghlansetmessages: + msg359832
2020-01-11 19:10:47mark.dickinsonsetmessages: + msg359817
2020-01-11 18:37:42mark.dickinsonsetnosy: + mark.dickinson
2020-01-11 06:59:44ncoghlancreate