就是例如整数是3位的话,100变成001,110变成011,有什么简单的算法没有啊,用循环就没意思了
解决方案
25
5
你还能再搞笑一些么?
http://graphics.stanford.edu/~seander/bithacks.html?1=1#BitReverseObvious
Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division):
unsigned char b; // reverse this (8-bit) byte
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
10
仅供参考:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int v;
int bitrev1(const int b) {
register int n;
n=b;
n=((n>> 1)&0x55555555)|((n<< 1)&0xaaaaaaaa);
n=((n>> 2)&0x33333333)|((n<< 2)&0xcccccccc);
n=((n>> 4)&0x0f0f0f0f)|((n<< 4)&0xf0f0f0f0);
n=((n>> 8)&0x00ff00ff)|((n<< 8)&0xff00ff00);
n=((n>>16)&0x0000ffff)|((n<<16)&0xffff0000);
return n;
}
int bitrev2(const int b) {
__asm {
push ebx
push ecx
mov ebx,b
mov ecx,32
nextbit:
rcl ebx,1
rcr eax,1
loop nextbit
pop ecx
pop ebx
}
}
int bitrev3(const int b) {
char bs[33],bs1[33],*ep;
itoa(b,bs1,2);
sprintf(bs,"%032s",bs1);
strrev(bs);
return strtol(bs,&ep,2);
}
void main() {
v=0x12345678;//0001 0010 0011 0100 0101 0110 0111 1000
printf("%08x\n",bitrev1(v));
printf("%08x\n",bitrev2(v));
printf("%08x\n",bitrev3(v));
}
//1e6a2c48
//1e6a2c48
//1e6a2c48