Search code examples
binaryfortran

exchange bits of an integer number in fortran


suppose you have the number 2 whose binary representation is 0010 How can you exchange bits located at positions 0 and 2, and bit at 1 and 3? so that the outcome is 1000 which is the number 8?

If I try using mvbits to exchange bits 0 and 2:

integer :: s1
s1= 2
call mvbits(s1,1,1,s1,3)

the result is the number 10

Is there an intrinsic function for such an operation?


Solution

  • mvbit copies the bits. It does not move the bits, where it seems you want to have the moved bits reset to zero. What you have discovered is essentially an allowed aliasing issue. You are copy 1 from 0010 to third position to get 1010. Consider the following:

    program foo
       implicit none
       integer(1) i, j
       j = 0
       i = 2
       call mvbits(i, 1, 1, j, 3) 
       write(*,'(B8.8,1X,B8.8,1X,2I3)') i, j, i, j
       call mvbits(i, 1, 1, j, 3) 
       write(*,'(B8.8,1X,B8.8,1X,2I3)') i, j, i, j
    end program foo
    

    Edit: Forgot to mention that integer(1) is not portable. It is an 8-bit integer with gfortran.