简体   繁体   中英

How do I reverse only the last 8 bits of an integer (32 bit) in C?

I have implemented the below function in C but it is not working properly.

int reverse(int org_num){
   int rev_num=0;
   int i=1;
   while(i<=8){
       int last_bit=org_num&1;
       rev_num=rev_num|last_bit;
       rev_num=rev_num<<1;
       org_num=org_num>>1;

       i=i+1;
   }
   return rev_num; }

You can do this to visualize what your code is doing.

void printBin(int num)
{
    const int N = 8;
    for (int i = 0; i < 8; ++i)
    {
        cout << ((num >> i) & 1);
    }
    cout << "\n";
}

void reverse(int org_num) {
    printBin(org_num);

    bool bit_back = 0;
    bool bit_front = 0;

    for (int i = 0, j = 7; i < 4; ++i, --j)
    {
        // obtaining the bits
        bit_back = (org_num >> i) & 1;
        bit_front = (org_num >> j) & 1;
        // zeroing out the bits
        org_num ^= (bit_front << j);
        org_num ^= (bit_back << i);
        // inserting the bits
        org_num |= (bit_back << j);
        org_num |= (bit_front << i);
    }

    printBin(org_num);
}

I solved the problem by breaking the loop for the last bit since that is not required.

    int reverse(int org_num){
       int rev_num=0;
       int i=1;
       while(i<=8){
          int last_bit=org_num&1;
          rev_num=rev_num|last_bit;
          if(i==8) {
            break;
          }
          rev_num=rev_num<<1;
          org_num=org_num>>1;
    
          i=i+1;
       }
       return rev_num;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM