将数字打包到一个位集中(python,按位操作) [英] Pack numbers into a bitset (python,bitwise operations)
问题描述
PIC微控制器具有完全无效的简单指令集格式.每条指令正好是14位长,由不同位长的各种数字组成.
The PIC microcontroller has a dead simple instruction set format. Each instruction is exactly 14 bits long, composed of a variety of numbers at differing bit lengths.
我正在尝试构建一个可以接收所有这些输入并构建代表该指令的数字的函数.
I am trying to build a function that can take all these inputs and build a number that represents that instruction.
这就是我一直在努力的工作:
This is what I have been trying to get working:
def fileRegOp(opcode, d, f):
out = opcode << 13
out = out | d << 7
out = out | f
return out
print "FIN:", bin(fileRegOp(1,True,15))
它输出
FIN:0b10000010001111
FIN: 0b10000010001111
看起来不错,除了位错误.我认为它应该显示为:
Which looks good, except the bits are the wrong way round. I think it should read:
FIN:0b00000111111000
FIN: 0b00000111111000
我已经看到了SO的解决方案,其中涉及使用循环来翻转位,但是我敢肯定有更好的方法.
I've seen solutions on SO that involve loops to flip the bits around, but I'm sure there's a better way.
编写此函数最优雅的方法是什么?
Whats the most elegant way to write this function?
有关指令集的更多详细信息:数据表参见第121,122页
More detail on the instruction set: Datasheet see page 121,122
推荐答案
您的班次错了.
您正在移动最高位的索引,这是不对的.您必须按每个字段的最低(最右)位的索引进行移位.
You are shifting by the index of the top-most bit, which isn't right. You must shift by the index of the lowermost (rightmost) bit in each field.
应该是:
def fileRegOp(opcode, d, f):
return (opcode << 8) | (d << 7) | f
这样可以进行一些编辑以在左侧添加填充零:
This gives, with some editing to add padding zeros on the left:
>>> bin(fileRegOp(1,True,15))
'0b00000110001111'
当然,对参数进行限制检查可能很明智.
Of course, it might be sensical to also limit-check the arguments.
这篇关于将数字打包到一个位集中(python,按位操作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!