| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- #!/usr/bin/env python3
- """课前零食:用 8 位显微镜观察 bitset 运算。"""
- from __future__ import annotations
- WIDTH = 8
- MASK = (1 << WIDTH) - 1
- def ask(prompt: str, default: str) -> str:
- try:
- return input(prompt).strip() or default
- except EOFError:
- return default
- def read_bits(prompt: str, default: str) -> int:
- raw = ask(prompt, default)
- if len(raw) != WIDTH or any(ch not in "01" for ch in raw):
- print(f"{raw!r} 不是 {WIDTH} 位 01 串;本次使用 {default}。")
- raw = default
- return int(raw, 2)
- def bits(value: int) -> str:
- return format(value & MASK, f"0{WIDTH}b")
- def members(value: int) -> list[int]:
- return [index for index in range(WIDTH) if (value >> index) & 1]
- def show(name: str, value: int) -> None:
- print(f"{name:>7} = {bits(value)},集合成员(最低位编号 0)={members(value)}")
- def main() -> None:
- print("Bitset 显微镜:左边是高位,最右边是编号 0。")
- a = read_bits("A(回车为 10110110): ", "10110110")
- b = read_bits("B(回车为 01101100): ", "01101100")
- show("A", a)
- show("B", b)
- operation = ask("操作:all / & / | / ^ / << / >>(回车为 all): ", "all")
- if operation in ("all", "&"):
- show("A & B", a & b)
- print(" 每一位都问一次:两盏灯是否同时亮?")
- if operation in ("all", "|"):
- show("A | B", a | b)
- if operation in ("all", "^"):
- show("A ^ B", a ^ b)
- if operation in ("all", "<<", ">>"):
- shift_text = ask("平移多少格(回车为 2): ", "2")
- try:
- shift = max(0, int(shift_text))
- except ValueError:
- shift = 2
- if operation in ("all", "<<"):
- show(f"A << {shift}", (a << shift) & MASK)
- print(" 左移出去的 1 不会搬家到另一端;它们离开了这个固定长度集合。")
- if operation in ("all", ">>"):
- show(f"A >> {shift}", a >> shift)
- print(" 右移时低位掉出集合,高位补 0。")
- print(f"\n置位数 popcount(A)={a.bit_count()}。8 位是演示,真实一字通常有 64 位。")
- if __name__ == "__main__":
- main()
|