Reversing bits of Python integer(反转 Python 整数的位)
问题描述
给定一个十进制整数(例如 65),如何反转 Python 中的底层位?即以下操作:
Given a decimal integer (eg. 65), how does one reverse the underlying bits in Python? i.e.. the following operation:
65 → 01000001 → 10000010 → 130
看来这个任务可以分解为三个步骤:
It seems that this task can be broken down into three steps:
- 将十进制整数转换为二进制表示
- 反转位
- 转换回十进制
第 2 步和第 3 步看起来非常简单(请参阅 this 和 this SO 问题与步骤#2) 相关,但我被困在步骤#1.第 1 步的问题是检索完整的十进制表示并填充零(即 65 = 01000001,而不是 1000001).
Steps #2 and 3 seem pretty straightforward (see this and this SO question related to step #2), but I'm stuck on step #1. The issue with step #1 is retrieving the full decimal representation with filling zeros (ie. 65 = 01000001, not 1000001).
我四处寻找,但似乎找不到任何东西.
I've searched around, but I can't seem to find anything.
推荐答案
int('{:08b}'.format(n)[::-1], 2)
您可以指定任何填充长度来代替 8.如果您想要真正花哨,
You can specify any filling length in place of the 8. If you want to get really fancy,
b = '{:0{width}b}'.format(n, width=width)
int(b[::-1], 2)
让您以编程方式指定宽度.
lets you specify the width programmatically.
这篇关于反转 Python 整数的位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:反转 Python 整数的位


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01