c++数值ab互换_怎么把一个数字的高低位互换

  • Post author:
  • Post category:其他


int main()

{

int a=2,b=0;

int i=0;

for(;i<32;i++)

{

b+=((a>>i)&1)<

}

printf(“%d\n”,b);

return 0;

}

晕刚回答了;还没有关

http://topic.csdn.net/u/20080504/10/9579d8d9-895a-492c-b597-4b3de3057058.html?seed=1285008557

//这是位翻转的

//互换是同样的技巧

#include

voidShowBit(unsigned int x, int n)

{

if (–n) ShowBit(x>>1, n);

printf(“%d”, x%2);

}

voidReverseBit(unsigned int* pValue)

{

unsigned int n = *pValue;

n = (n&0x55555555)<<1|(n&0xAAAAAAAA)>>1;

n = (n&0x33333333)<<2|(n&0xCCCCCCCC)>>2;

n = (n&0x0F0F0F0F)<<4|(n&0xF0F0F0F0)>>4;

n = (n&0x00FF00FF)<<8|(n&0xFF00FF00)>>8;

n = (n&0x0000FFFF)<<16|(n&0xFFFF0000)>>16;

*pValue = n;

}

int main()

{

unsigned int x = 0x6A;

ShowBit(x, 32); printf(“\n”);

ReverseBit(&x);

ShowBit(x, 32); printf(“\n”);

return 0;

}

楼上的方法参考<> 一般的方法可以这样来:

int reverse(unsigned x)

{

int m = 0, i;

unsigned mask = x;

for (i=0; i<32; i++)

{

m = (m <

mask >>= 1;

}

return m;

}

int main(int argc, char* argv[])

{

int a=1;

int highLow;

int lowHigh;

int result;

highLow=a>>16;//右移(舍弃右边的16位,左边高位移入0),实现了高位变低位

lowHigh=a<<16;//左移(舍弃左边的16位,右补0),实现了低位变高位

result=highLow+lowHigh;//相加就是结果拉,,,

cout<

return 0;

}

int main(int argc, char* argv[])

{

int a=1;

int highLow;

int lowHigh;

int result;

highLow=a>>16;//右移(舍弃右边的16位,左边高位移入0),实现了高位变低位

lowHigh=a

result=highLow+lowHigh;//相加就是结果拉,,,

cout

return 0;

}

ls正解,很好理解。

问题有歧异,lz最好举例说明下你的要求

楼主开了两个贴啊

up!

大家提出这么多方法了啊!

我再贴出一个,呵呵!

#include

using std::cout;

using std::endl;

using std::hex;

int reverseInt(int);

int main()

{

int a = 0x1fed1234;

cout<

int b = reverseInt(a);

cout<

system(“pause”);

}

int reverseInt(int a)

{

return ((a&0xffff0000) >>16) | ((a&0x0000ffff) <<16);

}

如果是位翻转,就看飞雪的了

左移右移就好了

UINT _b = 0xF2345678;

_asm

{

mov eax, _b

shl eax, 16

mov edx, _b

shr edx, 16

or eax, edx

mov _b, eax

}

printf(“0x%x\n”, _b);



版权声明:本文为weixin_36399948原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。