why is a negative shift value illegal?

Rainer Deyke root at rainerdeyke.com
Sun Jan 14 01:02:21 EST 2001


"Tim Peters" <tim.one at home.com> wrote in message
news:mailman.979430656.15673.python-list at python.org...
> Sorry, couldn't resist that.  Simpler answer is "why would they?".  shifts
> don't work that way in most other languages; seems of marginal utility at
> best; and would slow down all Python shifts because Python is implemented
in
> C and we could no longer use the native C shift (well, we can't anyway,
> because C doesn't define the behavior of signs on right shifts; or shifts
> greater than or equal to the bit size in either direction; and Python does
> define those cases -- but yet another test in the implementation maze sure
> wouldn't speed things up).

I don't buy the speed argument.  The speed penalty for one additional check
is insignificant compared to the overhead that already exists.  Adding the
negative shift values would actually yield a significant speed increase in
some areas.

Consider 16 bit color formats.  Red, green, and blue components are packed
into a single 16 bit value.  For any given 16 bit color format, each
component has a mask, from which can be derived its position and length.
For example:

Pixel format: rrrrrggggggbbbbb

red_mask = 0xf800
red_position = 11
red_length = 5
green_mask = 0x07e0
green_postion = 5
green_length = 6
blue_mask = 0x001f
blue_position = 0
blue_length = 5

To operate on an individual component, on needs to isolate it, shift it to
the right by its position, and promote it to an 8 bit value by shifting it
to the left:

red = ((color & red_mask) >> red_position) << (8 - red_length)

The left shift value can be precalculated, of course.  However, if negative
shift values were allowed, the two shifts could be reduced to a single
shift:

red_shift = red_postion + red_length - 8
red = (color & red_mask) >> red_shift

This is a significant speed increase, even if the actual shift takes
slightly longer.  Furthermore, allowing negative shift values would
automatically add support for strange pixel formats that assign more than 8
bits to a component (such as rrrggggggggggbbb).


--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list