Get nth byte of integer

瘦欲@ 提交于 2019-12-08 20:13:27

问题


I have the following integer:

target = 0xd386d209
print hex(target)

How can I print the nth byte of this integer? For example, expected output for the first byte would be:

0x09

回答1:


You can do this with the help of bit manipulation. Create a bit mask for an entire byte, then bitshift that mask the number of bytes you'd like. Mask out the byte using binary AND and finally bitshift back the result to the first position:

target = 0xd386d209
n = 0 # 0th byte
goal = 0xFF << (8 * n)
print hex((target & goal) >> (8 * n))

You can simplify it a little bit by shifting the input number first. Then you don't need to bitshift the goal value at all:

target = 0xd386d209
n = 0 # 0th byte
goal = 0xFF
print hex((target >> (8 * n)) & goal)



回答2:


>>> def print_n_byte(target, n):
...     return hex((target&(0xFF<<(8*n)))>>(8*n))
... 
>>> print_n_byte(0xd386d209, 0)
'0x9L'
>>> print_n_byte(0xd386d209, 1)
'0xd2L'
>>> print_n_byte(0xd386d209, 2)
'0x86L'



回答3:


This only involves some simple binary operation.

>>> target = 0xd386d209
>>> b = 1
>>> hex((target & (0xff << b * 8)) >> b * 8)
'0x9'
>>> hex((target & (0xff << b * 8)) >> b * 8)
'0xd2'



回答4:


def byte(number, i):
    return (number & (0xff << (i * 8))) >> (i * 8)


来源:https://stackoverflow.com/questions/32695714/get-nth-byte-of-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!