Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Bitwise Slicing
#6
(Aug-25-2020, 03:00 AM)Peter_Truman Wrote: If I went with
bits = [1 if x == "1" else 0 for x in f"{result:08b}"[-8:]] # takes only 8 LSB in case result > 2**8
Would that not simply leave me with a string called 'bits' - so effectively just masking out the lower 4 bits of result?

No, it's just compact. The first part (the f-string) converts the byte to the 8 LSB bits as a string object. f"{result:08b}"[-8:]

The next part goes through each character of the string one-by-one and converts it to a list of numbers, either 0 or 1. So the MSB is index 0 and the LSB is index 7, via a list comprehension. Expanding the loop, it would look like:

temp_list = []
for x in f"{result:08b}"[-8:]:
    if x == "1":
        temp_list.append(1)
    else:
        temp_list.append(0)
bits = temp_list
So at the end, you've got the list [1, 1, 1, 0, 0, 1, 1, 1]

It looks like there's also a PyPi module called bitstring. It could be that it has some functions that would be useful.
Reply


Messages In This Thread
Bitwise Slicing - by Peter_Truman - Aug-25-2020, 12:58 AM
RE: Bitwise Slicing - by micseydel - Aug-25-2020, 02:10 AM
RE: Bitwise Slicing - by bowlofred - Aug-25-2020, 02:52 AM
RE: Bitwise Slicing - by Peter_Truman - Aug-25-2020, 03:00 AM
RE: Bitwise Slicing - by bowlofred - Aug-25-2020, 03:23 AM
RE: Bitwise Slicing - by deanhystad - Aug-25-2020, 03:12 AM
RE: Bitwise Slicing - by Peter_Truman - Aug-25-2020, 06:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Program demonstrates operations of bitwise operators without using bitwise operations ShawnYang 2 2,604 Aug-18-2021, 03:06 PM
Last Post: deanhystad
  Bitwise ~ Operator muzikman 10 6,018 Feb-07-2021, 04:07 PM
Last Post: muzikman
  not bitwise ~15 1885 3 4,293 Oct-30-2019, 03:49 AM
Last Post: 1885
  understanding exponential and bitwise operators srm 1 2,704 Jun-15-2019, 11:14 AM
Last Post: ThomasL

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020