C语言实现二进制数1双向同步移动生成指定序列求助
Absolutely feasible! This is a neat symmetric bit-shifting pattern, and we can implement it with straightforward bitwise operations. Let's break this down:
Problem Breakdown
Your target sequence is a symmetric "inward-then-outward" movement of two 1s:
- Start with
0b10000001(1s at the extreme ends of an 8-bit value) - Move inward step-by-step:
0b01000010→0b00100100→0b00011000(1s meet in the middle) - Then reverse the movement to return to the starting value:
0b00100100→0b01000010→0b10000001
Implementation Logic
The core idea has two phases:
- Inward movement: Shift the left 1 right and the right 1 left each iteration, until the two 1s are adjacent.
- Outward movement: Reverse the inward steps to move the 1s back to the ends.
- Collect all intermediate values to form the full sequence.
Python Code Example
Here's a clean implementation that produces exactly your desired sequence:
def generate_bit_sequence(): # Starting value: 0b10000001 = 129 current = 0b10000001 sequence = [current] # Phase 1: Move 1s inward until they're adjacent while not (current & (current << 1)): # Isolate the rightmost and leftmost 1 bits right_bit = current & -current # Uses two's complement to get rightmost 1 left_bit = current while left_bit & (left_bit << 1): left_bit <<= 1 # Shift both bits toward the center new_left = left_bit >> 1 new_right = right_bit << 1 current = new_left | new_right sequence.append(current) # Phase 2: Reverse the inward steps (excluding the middle value to avoid duplication) sequence.extend(reversed(sequence[:-1])) # Format to 8-bit binary strings for exact matching formatted_sequence = [f"0b{format(num, '08b')}" for num in sequence] return formatted_sequence # Test the function result = generate_bit_sequence() print(' '.join(result))
Output
Running this code will print:0b10000001 0b01000010 0b00100100 0b00011000 0b00100100 0b01000010 0b10000001
Key Details Explained
- Isolating bits:
current & -currentis a trick to grab the rightmost 1 bit quickly. For the leftmost 1, we keep shifting left until shifting again would cause an overlap (indicating we've found the leftmost set bit). - Inward stop condition:
current & (current << 1)checks if any two 1s are adjacent—once this is true, we've reached the middle of the sequence. - Symmetric reverse: By reversing the first part of the sequence (excluding the middle value) and appending it, we get the outward movement for free, avoiding redundant code.
This logic translates easily to other languages like C/C++ or JavaScript—just adapt the bitwise operations to match the language's integer handling.
内容的提问来源于stack exchange,提问作者Jaime Andrés Avendaño Villa
相关产品推荐
相关产品推荐

