My brain, of course, wouldn't let go, so I came up with something much more elegant, somewhere, half asleep on the plane:
public static final long reverse(long l) {
l = (l>>32)|(l<<32);
l = ((l>>16)&0x0000ffff0000ffffl)|((l<<16)&0xffff0000ffff0000l);
l = ((l>>8)&0x00ff00ff00ff00ffl)|((l<<8)&0xff00ff00ff00ff00l);
l = ((l>>4)&0x0f0f0f0f0f0f0f0fl)|((l<<4)&0xf0f0f0f0f0f0f0f0l);
l = ((l>>2)&0x3333333333333333l)|((l<<2)&0xccccccccccccccccl);
l = ((l>>1)&0x5555555555555555l)|((l<<1)&0xaaaaaaaaaaaaaaaal);
return l;
}
This is 12 shifts, 10 ANDs, 6 ORs.
No comments:
Post a Comment