swapping the bits in a byte

Started by
5 comments, last by hplus0603 18 years, 8 months ago
I am wondering about an efficient method to store things in a little "bit" order on x86:

[FEDCBA98][76543210] <--big endian bits
[76543210][FEDCBA98] <- little endian bits
[01234567][89ABCDEF] <- my bits

This seems to require swapping the bits in the bytes of a register, and all the solutions that I've come up with for this are very slow. I don't see anything in the way of an instruction for this, although I'm not incredibly experienced with x86 assembly. (Yes I have googled this) Thanks, ~SPH
AIM ME: aGaBoOgAmOnGeR
Advertisement
You do realize that you don't have to swap actual bits around if you're concerned about endian-ness between (say) Mac and Windows? It's only the bytes that you need to worry about.

But if for some reason you really want to do it probably the simplest way is a 256-entry lookup table.

Actually your examples don't make any sense to me either. It's looks like all you're doing is flipping the high bit of each nibble.
-Mike
Hey sweet, it's another excuse to link to my most favorite page ever! They list a bunch of methods.
x86 asm:
bswap reg

C
unsigned short htons(unsigned short x){    return x >> 8 | x << 8;}    unsigned htonl(unsigned x){    return htons(x >> 16) | htons(x & 0xFFFF) << 16;}    


edit: this doesn't solve the problem, this is for big<->little endian byte order... the bits are in another castle.

[Edited by - DigitalDelusion on August 15, 2005 6:28:30 PM]
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
var=((var&0x0f)<<4)|((var&0xf0)>>4);
var=((var&0x33)<<2)|((var&0xcc)>>2);
var=((var&0x55)<<1)|((var&0xaa)>>1);
Quote:Original post by pinacolada
Hey sweet, it's another excuse to link to my most favorite page ever! They list a bunch of methods.

+! I'd seen this page a while ago but never kept the link. Some of this stuff really comes in handy when you want to write code that no one else is going to understand =b
Quit screwin' around! - Brock Samson
DigitalDelusion: that doesn't do what he wants.

A lookup table is the most obvious solution, although the 64-bit arithmetic operations are cute.
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement