递归位反转程序

时间:2015-05-03 07:31:47

标签: c recursion reverse bit

递归反向位程序。

#include <stdio.h>
#include <conio.h>

void displayBits( unsigned value );
void reverseBits( unsigned value, unsigned c );

int main( void )
{
    unsigned value;
    unsigned c = 32;

    printf( "Enter a unsigned integer: " );
    scanf( "%u", &value );   

    displayBits( value );
    printf( "%10s", "Reversed:    " );
    reverseBits( value , c );

    getche();
    return 0;
}

void displayBits( unsigned value )
{
     unsigned c;
     unsigned mask = 1 << 31;

     printf( "%10u = ", value );

     for( c = 1; c <= 32; c++ ){
          putchar( value & mask ? '1' : '0' );
          value <<= 1;
          if( c % 8 == 0 )
              putchar( ' ' );

          }//end for    
     putchar( '\n' );

}

void reverseBits( unsigned value, unsigned c )
{
     unsigned mask = 1 << 31;

     if( c == 0 ){
         return;

         }//end if

     else{     
          value <<= 1;
          reverseBits( value , c - 1 );
          putchar( value & mask ? '1' : '0' );
          if( c % 8 == 0 ){
              putchar( ' ' );

              }//end if
          }//end else
}

输入15时输出

01111000 00000000 00000000 00000000

而不是

11110000 00000000 00000000 000000000. 

1 个答案:

答案 0 :(得分:0)

 else{     
      value <<= 1;//<-- Value has been changed before it can be used
      reverseBits( value , c - 1 );
      putchar( value & mask ? '1' : '0' );
      if( c % 8 == 0 ){
          putchar( ' ' );

          }//end if
      }//end else

替换为

else {
    reverseBits(value << 1, c - 1 );
    putchar( value & mask ? '1' : '0' );
    if( c % 8 == 0 ){
        putchar( ' ' );
    }
}