Advertisement

Swapping single bits in assembler

Started by July 21, 2001 04:35 AM
3 comments, last by chimplp 23 years, 7 months ago
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.
I don''t quite understand what you want to do. Could you post your code?

Advertisement
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 :<br><br><pre><br>; eax = the variable which will have bits 18 and 2 swapped<br><br>mov ebx, eax ; temporary copy<br>and ebx, #(1<<18) | (1<<2) ; mask bits in copy<br>mov ecx, ebx ; make another copy<br>shl ebx, #(18-2) ; shift low bit into where high is<br>shr ecx, #(18-2) ; shift high bit into where low is<br>and eax, #~((1<<18)|(1<<2)) ; clear both bits in original<br>or eax, ebx ; set new low bit<br>or eax, bcx ; set new high bit<br> </pre> <br><br>–<br>Simon O''''Connor<br>Creative Asylum Ltd<br><A HREF="http://www.creative-asylum.com">www.creative-asylum.com</A>

Simon O'Connor | Technical Director (Newcastle) Lockwood Publishing | LinkedIn | Personal site

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

This topic is closed to new replies.

Advertisement