Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

后端 未结 26 1842
情深已故
情深已故 2020-11-22 06:08

What is the most efficient algorithm to achieve the following:

0010 0000 => 0000 0100

The conversion is from MSB->LSB to LSB->MSB. All bits

26条回答
  •  生来不讨喜
    2020-11-22 07:10

    Presuming that you have an array of bits, how about this: 1. Starting from MSB, push bits into a stack one by one. 2. Pop bits from this stack into another array (or the same array if you want to save space), placing the first popped bit into MSB and going on to less significant bits from there.

    Stack stack = new Stack();
    Bit[] bits = new Bit[] { 0, 0, 1, 0, 0, 0, 0, 0 };
    
    for (int i = 0; i < bits.Length; i++) 
    {
        stack.push(bits[i]);
    }
    
    for (int i = 0; i < bits.Length; i++)
    {
        bits[i] = stack.pop();
    }
    

提交回复
热议问题