44 lines
731 B
Python
44 lines
731 B
Python
|
|
||
|
def int2byte(n):
|
||
|
if n >= 2 ** 8:
|
||
|
raise Exception('a byte can only contain a number smaller then %s' % (2 ** 8))
|
||
|
|
||
|
bits = [0] * 8
|
||
|
|
||
|
for i in range(8):
|
||
|
j = 7 - i
|
||
|
c = 2 ** j
|
||
|
|
||
|
if c <= n:
|
||
|
n -= c
|
||
|
bits[i] = 1
|
||
|
|
||
|
return bits
|
||
|
|
||
|
|
||
|
def byte2int(byte):
|
||
|
result = 0
|
||
|
for i in range(len(byte)):
|
||
|
j = 7 - i
|
||
|
c = 2 ** i
|
||
|
|
||
|
result += c * byte[j]
|
||
|
|
||
|
return result
|
||
|
|
||
|
def test(x):
|
||
|
b = int2byte(x)
|
||
|
print(x, '\t', b, '\t', byte2int(b))
|
||
|
|
||
|
|
||
|
|
||
|
def swapMSB2LSB(origin, target, numberOfBits):
|
||
|
target[len(target) - numberOfBits:] = origin[0:numberOfBits]
|
||
|
return target
|
||
|
|
||
|
def extractLSB(byte, numberOfBits):
|
||
|
newByte = [0] * 8
|
||
|
newByte[0:numberOfBits] = byte[len(byte) - numberOfBits:]
|
||
|
return newByte
|
||
|
|