位运算对称的算法是什么

C语言 码拜 8年前 (2016-05-20) 1073次浏览
就是例如整数是3位的话,100变成001,110变成011,有什么简单的算法没有啊,用循环就没意思了
解决方案

25

5

引用:
Quote: 引用:
Quote: 引用:
Quote: 引用:

这是实现字节位逆序最快的算法,你好好领会吧。位运算对称的算法是什么

这种有什么好领会的,毫无技术含量,最快的是这个,64位,b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;

你这么说太棒槌了,这个算法需要mul、div、and,除法多慢你不懂啊,慢得没边了,应该都没有查表法1/5的性能。
另外,它这个”64位”是说用到了64位运算,不是能求64位数逆序,结果还是8位的。

不是64位是什么,还8位,真是搞笑了,查表能查到几位,内存放的下

你还能再搞笑一些么?
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

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明位运算对称的算法是什么
喜欢 (0)
[1034331897@qq.com]
分享 (0)