曼彻斯特编码

# -*- coding: utf-8 -*-
import struct
import math
def long_to_bytes(n):
s = b''
pack = struct.pack
while n > 0:
s = pack('>I', n & 0xffffffff) + s
n = n >> 32
for i in range(len(s)):
if s[i] != b'\000'[0]:
break
else:
s = b'\000'
i = 0
s = s[i:]
return s

#字节逆序
def byteinvert(str_bin):
ret=''
for i in range(len(str_bin)//8):
ret+=str_bin[i*8:i*8+8][::-1]
return ret

#标准曼彻斯特
def MCST_stand(str_bin):
ret=''
for i in range(len(str_bin)//2):
x=str_bin[i*2:i*2+2]
if x=='01':
ret+='0'
elif x=='10':
ret+='1'
else:
return 'stand manchester decode wrong!'
return ret

#IEEE规范的曼彻斯特
def MCST_IEEE(str_bin):
ret=''
for i in range(math.ceil(len(str_bin)/8)):
x=str_bin[i*2:i*2+2]
if x=='01':
ret+='1'
elif x=='10':
ret+='0'
else:
return 'stand manchester decode wrong!'
return ret

#差分曼彻斯特
def MCST_diff(str_bin):
ret=''
for i in range(0,len(str_bin)//2-1):
x1=str_bin[i*2:i*2+2]
x2=str_bin[i*2+2:i*2+4]
if x1==x2:
ret+='0'
else:
ret+='1'
return ret

if __name__ == "__main__":
str_hex='9a9a9a6a9aa9656699a699a566995956996a996aa6a965aa9a6aa596a699665a9aa699655a696569655a9a9a9a595a6965569a59665566955a6965a9596a99aa9a9566a699aa9a969969669aa6969a9559596669'
#str_bin='0101010101010101'
str_bin=str(bin(int(str_hex,16)))[2:]

m1=MCST_IEEE(str_bin)
m2=MCST_stand(str_bin)
m3=MCST_diff(str_bin)
print('\nIEEE曼彻斯特:')
print(m1)
print(hex(int(m1,2)))
print(long_to_bytes(int(m1,2)))
print('\n 标准曼彻斯特:')
print(m2)
print(hex(int(m2,2)))
print(long_to_bytes(int(m2,2)))
print('\n 差分曼彻斯特:')
print(m3)
print(hex(int(m3,2)))
print(long_to_bytes(int(m3,2)))
print('\n=============字节逆序=============')
m1=byteinvert(m1)
m2=byteinvert(m2)
m3=byteinvert(m3)
print('\nIEEE曼彻斯特:')
print(m1)
print(hex(int(m1,2)))
print(long_to_bytes(int(m1,2)))
print('\n 标准曼彻斯特:')
print(m2)
print(hex(int(m2,2)))
print(long_to_bytes(int(m2,2)))
print('\n 差分曼彻斯特:')
print(m3)
print(hex(int(m3,2)))
print(long_to_bytes(int(m3,2)))