Created
January 22, 2019 17:33
-
-
Save roxsula/7fd465c9fd54456b6b3c2201df15c579 to your computer and use it in GitHub Desktop.
make endianness conversion between big endian and little endian
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def invert_endianness(number): | |
new_bits = [] | |
total_bits = number.bit_length() | |
check_len = True | |
bits = 8 | |
while(check_len): | |
if (bits - total_bits) >= 0: | |
check_len = False | |
else: | |
bits *= 2 | |
shift_back = bits - 8 | |
shift = 8 | |
mask = 0xFF | |
bits = bits//8 | |
new_endian = 0x00000000 | |
for i in range(bits): | |
if i==0: | |
new_bits.append(number & mask) | |
else: | |
new_bits.append((number >> shift) & mask) | |
shift += 8 | |
for i in range(bits): | |
new_endian |= (new_bits[i] << shift_back) | |
shift_back -= 8 | |
return new_endian | |
big_endian = 0x00020804 | |
print('0x{0:0{1}X}'.format(big_endian,8)) | |
print('0x{0:0{1}X}'.format(invert_endianness(big_endian),8)) | |
big_endian = 0x0000010000040880 | |
print('0x{0:0{1}X}'.format(big_endian,16)) | |
print('0x{0:0{1}X}'.format(invert_endianness(big_endian),16)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment