简体   繁体   中英

how to make 16bit to 8bit like that 0x0300 to 0x03 and 0x00 by python?

how to make 16bit to 8bit like that 0x0300 to 0x03 and 0x00 by python?

i try to it like that

reg = 0x0300
print(reg[0:4], reg[4::])..

it show me that 'int' object is not subscriptable

reg = 0x0316
regbinary = bin(reg)
print(regbinary)
regBotoom = regbinary[-8::]
print(regBotoom)
result = hex('0b'+regBotoom)
print(result)


it show me that

0b1100010110

00010110

TypeError: 'str' object cannot be interpreted as an integer

You can get lower and higher 8 bits with bitwise AND and shifting:

reg = 0x0316
lowBits = reg & 0xFF
highBits = (reg >> 8) & 0xFF
print(lowBits)
print(highBits)

Perhaps you're after the answer @jafarlihi gave, where reg is really just an int and you shift its value to get the values you're after.

However, you may also want to see this:

import struct

reg = 790

regb = struct.pack('h', reg)
print(regb)

msb, lsb = struct.unpack('bb', regb)
print(msb, lsb)

regb_2 = struct.pack('bb', msb, lsb)
print(regb, regb_2)

value = struct.unpack('h', regb)
print(reg, value)

Result:

b'\x16\x03'
22 3
b'\x16\x03' b'\x16\x03'
790 (790,)

Bitwise Operators:

x = 0x4321
y = x >> 8 
  = 0x43
z = x & 0x00ff
  = 0x21

You can not manipulate an int like you are trying to do without converting it to a string first.

reg = 0x0300
print(hex((reg >> 8) & 0xFF))
print(hex(reg & 0xFF))

Output:

0x3
0x0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM