[Inputs]:
地址:0x001c,16 位宽。
重置:0x0
这是 PIN 16..31 的位字段寄存器。
[问题]:如何选择 PIN 17?
[我的解决方案]:这是正确的做法吗:
def select_pin(pin):
lowstate = 0x0000
highstate = 0x001c
pin_hex = int(str(pin), 16)
responsive = highstate-pin_hex
inverted = hex(responsive ^ 0xFFFF)
print(inverted)
select_pin(17)
老实说,我对这个领域有一个理论差距,我什至不确定如何制定我的问题以在 Google 中找到有关它的一些信息,任何帮助将不胜感激。
假设(寄存器(值位表示引脚值,其中每个引脚号表示LSB->MSB(从右到左(的位索引,您所要做的就是简单的按位和介于:
- 价值
- 一个掩码,它只设置了一个位(在所需引脚的位置(,而所有其他位都被重置
要提取您感兴趣的位(PIN( 值,请执行以下操作:
>>> reg = 0x001C0000 # Hi Word, Lo Word >>> >>> reg_bin_repr = "{0:032b}".format(0x001C0000) # For visualization purposes only >>> reg_bin_repr '00000000000111000000000000000000' >>> >>> for idx, val in enumerate(reversed(reg_bin_repr)): # Each bit with its value (right -> left) ... print("Bit (pin) {0:02d}: {1:s}".format(idx, val)) ... Bit (pin) 00: 0 Bit (pin) 01: 0 Bit (pin) 02: 0 Bit (pin) 03: 0 Bit (pin) 04: 0 Bit (pin) 05: 0 Bit (pin) 06: 0 Bit (pin) 07: 0 Bit (pin) 08: 0 Bit (pin) 09: 0 Bit (pin) 10: 0 Bit (pin) 11: 0 Bit (pin) 12: 0 Bit (pin) 13: 0 Bit (pin) 14: 0 Bit (pin) 15: 0 Bit (pin) 16: 0 Bit (pin) 17: 0 Bit (pin) 18: 1 Bit (pin) 19: 1 Bit (pin) 20: 1 Bit (pin) 21: 0 Bit (pin) 22: 0 Bit (pin) 23: 0 Bit (pin) 24: 0 Bit (pin) 25: 0 Bit (pin) 26: 0 Bit (pin) 27: 0 Bit (pin) 28: 0 Bit (pin) 29: 0 Bit (pin) 30: 0 Bit (pin) 31: 0 >>> >>> # And the function >>> def pin_value(register_value, pin_number): ... return 1 if register_value & (1 << pin_number) else 0 ... >>> >>> pin_value(reg, 17) 0 >>> pin_value(reg, 18) 1
作为旁注,在处理数字时,您不必将它们转换为相同的基数,将其转换为不同的基数时,值不会更改,只有其表示形式会更改:
>>> i0 = 1 >>> i1 = 0x19 >>> >>> i0 + i1 26 >>> i1 25 >>> hex(i1) '0x19' >>> int(hex(i1), 16) 25
位掩码只是以整数表示法2**pin
。
如果您有
# alternating increasing amounts of 0/1
reg = int("10110011100011110000111110000010",2) # 4294967295
def get_pin(value, pin):
return 1 if (value & 2**pin) > 0 else 0
for p in range(33):
print(f"{2**p:>10} is {get_pin(reg,p)}")
1 is 0
2 is 1
4 is 0
8 is 0
16 is 0
32 is 0
64 is 0
128 is 1
256 is 1
512 is 1
1024 is 1
2048 is 1
4096 is 0
8192 is 0
16384 is 0
32768 is 0
65536 is 1
131072 is 1
262144 is 1
524288 is 1
1048576 is 0
2097152 is 0
4194304 is 0
8388608 is 1
16777216 is 1
33554432 is 1
67108864 is 0
134217728 is 0
268435456 is 1
536870912 is 1
1073741824 is 0
2147483648 is 1