[Tutor] [spoiler] Re: Shifting arrays as though they are a 'word'

Steven D'Aprano steve at pearwood.info
Mon Oct 8 20:04:35 EDT 2018


On Mon, Oct 08, 2018 at 09:16:16AM -0400, Chip Wachob wrote:

> - What follows is a mini version, the array could be any size up to 64 bytes
> 
> input:  10010010 . 11101111 . 01010011
>
> shift 'x' (for example, I'll use 1)
> 
> output: 01001001 . 01110111 . 10101001

The first two seem to be simple right bit-shift:

10010010 -> 01001001
11101111 -> 01110111

but the third seems to be something completely different, neither a left 
nor a right shift:

01010011 -> 10101001

A left-bit shift would give this:  10100110
and a right shift would give this: 00101001

So now I don't know what you want.

[...]
> The above are not actual data that have been manipulated by the
> software but illustrations of observations.  The real data is 'random'
> so I'm doing the best to recall from memory what happens.

Seriously, "this is what I vaguely remember happening" is no way to 
debug software. Show us *actual data* with *actual results* and maybe we 
can help, otherwise we're just pissing into the wind here.


[...]
> Ideally, I'd love to be able to say :
> 
> # here's the array / list
> rx_data = []
> 
> # read through all the bytes
> # stash the results into the list
> for x in range (bytes_of_data):
>    rx_data[x] = read_data()[0]
> 
> # bit shift the entire lot
> rx_data = rx_data >> bits_to_shift.
> 
> Which would provide me with the output described above.

Take your byte-array returned from read_data, the *lot* of it, not just 
the first byte. Convert to an int, and shift the int.

py> b = bytearray(4)  # work with four bytes
py> b[1] = 255  # fill in some non-zero values
py> b[2] = 127
py> b
bytearray(b'\x00\xff\x7f\x00')
py> n = int.from_bytes(b, 'big')
py> hex(n)
'0xff7f00'
py> bin(n >> 1)
'0b11111111011111110000000'
py> bin(n << 1)
'0b1111111101111111000000000'

Does that help?




-- 
Steve


More information about the Tutor mailing list