获取整数的第n个字节 [英] Get nth byte of integer

查看:95
本文介绍了获取整数的第n个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下整数:

target = 0xd386d209
print hex(target)

如何打印此整数的第n个字节?例如,第一个字节的预期输出将是:

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

0x09


推荐答案

您可以在位操作的帮助下完成此操作。为整个字节创建一个位掩码,然后将其移位以屏蔽所需的字节数。使用二进制AND屏蔽掉字节,最后将结果位移回第一个位置:

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))

您可以通过先移动输入数字来简化它。那么您根本不需要对 goal 的值进行位移位:

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)

这篇关于获取整数的第n个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆