#### Archived

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

# Swapping single bits in assembler

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

## 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 on other sites
I don''t quite understand what you want to do. Could you post your code?

##### 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 swappedmov ebx, eax                  ; temporary copyand ebx, #(1<<18) | (1<<2)    ; mask bits in copymov ecx, ebx                  ; make another copyshl ebx, #(18-2)              ; shift low bit into where high isshr ecx, #(18-2)              ; shift high bit into where low isand eax, #~((1<<18)|(1<<2))   ; clear both bits in originalor  eax, ebx                  ; set new low bitor  eax, bcx                  ; set new high bit

--
Simon O''''Connor
Creative Asylum Ltd
www.creative-asylum.com

##### 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 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.

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 9
• 12
• 20
• 12
• 13
• ### Forum Statistics

• Total Topics
632147
• Total Posts
3004444

×