#ifndef BITSREVERSE_H_
#define BITSREVERSE_H_
#include<iostream>
using namespace std;
class Bit
{
public:
typedef unsigned int uint;
/*
* 交换无符号数字x的i,j位
* 曾出现两处书写错误 1. 进行异或交换时候,构造bit时候<< 误写成>>. 2.循环交换时候n/2误写成n.
*/
int swapbits(uint &x, uint i, uint j)
{
uint n = sizeof(uint);
n = n * 8;
if (i >= n || j >= n)
return -1;
uint bj = (x >> j) & 0x1;
uint bi = (x >> i) & 0x1;
if (bj ^ bi) /* i,j bit 的值不相同的时候进行交换 */
{
x = x ^ ((0x1 << i) | (0x1 << j)); /* 采用异或操作进行交换 */
}
return 0;
}
int reversebits(uint &x)
{
uint n = sizeof(uint);
n = n * 8;
for (uint i = 0; i < n / 2; i++)/* 字符串反序 */
swapbits(x, i, n - i - 1);
return 0;
}
void output(uint x)
{
cout << hex << x << endl;
}
};
#endif
反序一个无符号整数x 不占用额外的空间 采用异或操作
最新推荐文章于 2023-05-25 22:19:31 发布