Swapping bits

New to FreeBASIC? Post your questions here.
Post Reply
newby12
Posts: 33
Joined: Dec 26, 2021 1:57

Swapping bits

Post by newby12 »

dim as string n2 = "101100"

print n2

swap mid( n2 , 5 , 2 ) , mid( n2 , 1 , 2 )

print n2

The swap errors , the compiler can't swap mid sequences.. I don't know if its a compiler error or just bad code??
Maybe it would be a "Feature Request"?
jj2007
Posts: 2326
Joined: Oct 23, 2016 15:28
Location: Roma, Italia
Contact:

Re: Swapping bits

Post by jj2007 »

Technically speaking, you want to swap bytes in a string, not bits. It can be done, of course:

Code: Select all

dim as string n2 = "101100011111111abc"
print n2

asm
  mov eax, [n2]	' get string address
  mov edx, eax	' make a copy
lbl1:
  mov cl, [eax]
  push ecx
  inc eax
  test cl, cl
  jne lbl1
  pop ecx		' discard nullbyte
lbl2:
  pop ecx		' get last valid byte
  mov [edx], cl	' move to start of string
  inc edx
  cmp eax, edx
  ja lbl2
  push ecx		' correct the stack
end asm

'swap mid( n2 , 5 , 2 ) , mid( n2 , 1 , 2 )

print n2
Sleep
Output:

Code: Select all

101100011111111abc
cba111111110001101
paul doe
Moderator
Posts: 1730
Joined: Jul 25, 2017 17:22
Location: Argentina

Re: Swapping bits

Post by paul doe »

newby12 wrote:...
The swap errors , the compiler can't swap mid sequences.. I don't know if its a compiler error or just bad code??
...
Of course it errs. What exactly are you swapping there? The results of two functions? How is that meaningful in any way?
fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Swapping bits

Post by fxm »

That does not work because the MID (Function) returns by value and not by reference.
Instead, you can swap byte elements inside the string characters by using the Operator [] (String index) which returns by reference:

Code: Select all

dim as string n2 = "101100"

print n2

'swap mid( n2 , 5 , 2 ) , mid( n2 , 1 , 2 )
swap n2[4], n2[0]
swap n2[5], n2[1]

print n2
Post Reply