1

I would like to find a way to reverse the bits of each character in a string using python.

For example, if my first character was J, this is ASCII 0x4a or 0b01001010, so would be reversed to 0x52 or 0b01010010. If my second character was K, this is 0b01001011, so would be reversed to 0xd2 or 0b11010010, etc.

The end result should be returned as a string.

Speed is my number one priority here, so I am looking for a fast way to accomplish this.

5
  • This may help: stackoverflow.com/questions/12681945/… Commented Apr 6, 2019 at 14:59
  • What's your current method, and what's the specific performance issue? Commented Apr 6, 2019 at 15:02
  • As you need str as output and want replace each character with single character, I suggest you to investigate translate method of str. Commented Apr 6, 2019 at 15:03
  • @jonrsharpe I have added my current best method as an answer. There are no specific performance issues, I would just like it to be as fast as is reasonably possible. Commented Apr 6, 2019 at 16:34
  • @OlivierMelançon Thank you, I used this to aid in my answer. Commented Apr 6, 2019 at 16:34

3 Answers 3

3

If speed is your goal and you are working with ASCII so you only have 256 8-bit values to handle, calculate the reversed-byte values beforehand and put them in a bytearray, then look them up by indexing into the bytearray.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your advice. I have added my own answer which implements this.
1

After taking on board the advice, here is my solution:

# Pre-populate a look-up array with bit-reversed integers from 0 to 255
bytearray = []
for i in range(0, 256):
    bytearray.append(int('{:08b}'.format(i)[::-1], 2))

# Reverses the bits of each character in the input string and returns the result
# as a string
def revstr(string):
    return ''.join([chr(bytearray[ord(a)]) for a in list(string)])

print "JK".encode("hex")         # 0x4a4b
print revstr("JK").encode("hex") # 0x52d2

Comments

0
 a=bin(ord("a"))
'0b'+a[::-1][0:len(a)-2]

If you want to do it for a lot of characters, then there are only 256 ascii characters. Store the reversed strings in a hashmap and do lookups on the hashmap. Time complexity of those lookups is O(1), but there's a fix setup time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.