python反转整数内的二进制模式 [英] python reverse a binary pattern within an integer

查看:169
本文介绍了python反转整数内的二进制模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在python中反转二进制数字?

Is there a fast possibility to reverse a binary number in python?

示例:我的16位二进制数0000000000001011中的数字为11.现在,我正在搜索 fast 函数f,该函数返回1101000000000000(十进制53248).查找表不是解决方案,因为我希望它可以扩展到32位数字.谢谢您的努力.

Example: I have the number 11 in binary 0000000000001011 with 16 Bits. Now I'm searching for a fast function f, which returns 1101000000000000 (decimal 53248). Lookup tables are no solutions since i want it to scale to 32Bit numbers. Thank you for your effort.

性能.我多次测试了所有2 ^ 16模式的代码.

Performances. I tested the code for all 2^16 pattern several times.

  • 获胜者是部分查找表:30ms

  • winner are the partially look up tables: 30ms

第二个int(format(num, '016b')[::-1], 2):56ms

第三次x = ((x & 0x00FF) << 8) | (x >> 8):65毫秒

我没想到我的方法如此之慢,但确实如此. 大约320ms.使用+而不是|进行小的改进300毫秒

I did not expect my approach to be so horribly slow but it is. approx. 320ms. Small improvement by using + instead of | 300ms

bytes(str(num).encode('utf-8'))为第二名而战 该代码未提供有效答案.最可能是因为我做了一个 再次将它们转换为整数会导致错误.

bytes(str(num).encode('utf-8')) fought for the 2nd place but somehow the code did not provide valid answers. Most likely because I made a mistake by transforming them into an integer again.

非常感谢您的投入.我很惊讶.

thank you very much for your input. I was quite surprised.

推荐答案

使用小的8位查找表可能会更快:

This might be faster using small 8-bit lookup table:

num = 11
# One time creation of 8bit lookup
rev = [int(format(b, '08b')[::-1], base=2) for b in range(256)]

# Run for each number to be flipped.
lower_rev = rev[num & 0xFF] << 8
upper_rev = rev[(num & 0xFF00) >> 8]
flipped = lower_rev + upper_rev

这篇关于python反转整数内的二进制模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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