epsilon_j
epsilon_j

Reputation: 335

How to reverse the bits of each character in a string using python

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.

Upvotes: 1

Views: 193

Answers (3)

epsilon_j
epsilon_j

Reputation: 335

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

Upvotes: 1

behold
behold

Reputation: 556

 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.

Upvotes: 0

BoarGules
BoarGules

Reputation: 16942

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.

Upvotes: 3

Related Questions