Advertisement Jump to content


This topic is now archived and is closed to further replies.


Swapping single bits in assembler

This topic is 6391 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can anyone think of a quick way of swapping two bits in a 32 bit variable in x86 asm? I have a rather convoluted way at the moment using bt, btc and bts but it''s about 25 ops and it seems OTT for such a simple task.

Share this post

Link to post
Share on other sites
I assume you mean swapping two arbitrary bits of a variable (ie. the contents of say bit 2 get copied to bit 18 and the previous contents of bit 18 go bit 2).
I also assume you have registers spare and that you know at assemble time what the two bits are. Off the top of my head and totally unoptimised [I have an idea for an even shorter method, but I''d rather test it properly before I suggest it]:

; eax = the variable which will have bits 18 and 2 swapped

mov ebx, eax ; temporary copy
and ebx, #(1<<18) | (1<<2) ; mask bits in copy
mov ecx, ebx ; make another copy
shl ebx, #(18-2) ; shift low bit into where high is
shr ecx, #(18-2) ; shift high bit into where low is
and eax, #~((1<<18)|(1<<2)) ; clear both bits in original
or eax, ebx ; set new low bit
or eax, bcx ; set new high bit

Simon O''''Connor
Creative Asylum Ltd

Share this post

Link to post
Share on other sites
That''s cool, but my original problem is that I have a bitfield that I want to randomly fill with x number of set bits. So I fill the bitfield with how many bits I want set, then mix them all up, hence the bit swapping problem. The bitfield is part of an AI response that I want to randomise.

Share this post

Link to post
Share on other sites
What about just using a random number generator and do something like:

int number = 0;
for( int i = 0; i < numBits; i++ )
int bit = rand() % 31;
number |= 1 << bit;

You''d have to make sure you don''t set the same bit twice though.

War Worlds - A 3D Real-Time Strategy game in development.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!