I’m trying to convert a string to a big endian but due to my lack of experience with bit shifting etc, I’ve got stuck with the following so far:
def my_func(self, b):
a = [(len(b)+3) >> 2]
for i, val in enumerate(b):
a[i>>2] |= ord(b[i]) << (24-(i & 3)*8)
return a
The above returns the error
a[i>>2] |= ord(b[i]) << (24-(i & 3)*8), and also never gets further through the loop index than #4.
IndexError: list index out of range
The error message is pointing to the a[] list.
Can anyone see what I’m doing wrong here? I’m porting this from JavaScript so that may be the issue (link to that http://pastebin.com/GKE3AeCm )
Without resorting to other methods, your code just needs to be adjusted more correctly from the Javascript version. In Javascript you are creating an
Arrayof certain length, but in your Python code you always create a list of size 1. Here is it corrected:So what you are doing is considering sequences of 4 objects as being raw bytes and unpacking them to build an integer. Using
struct, the correct way would be to be explicit about your data being bytes and passing it as such: