exchange position bit

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
marcelo_bahia
Posts: 4
Joined: 15 May 2009, 10:44 AM
Location: argentine

exchange position bit

Post by marcelo_bahia »

I need to read individual bits in a byte and put some of those bits in a byte in different positions. you can help me , thanks
for example:

dim a as byte

dim b as byte

dim c as byte

a=bx 0001 1101 ' (a7....a0) decimal=29
b=bx 1000 1100 ' (b7....b0) decimal=140

eg I need to exchange these bits

c=000b1 b0a2a1a0 =0000 0101 ´decimal=5
GTBecker
Posts: 616
Joined: 17 January 2006, 19:59 PM
Location: Cape Coral

exchange position bit

Post by GTBecker »

Code: Select all

c = ((b and 3) * 8) or (a and 7)

Tom
Tom
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: exchange position bit

Post by dkinzer »

GTBecker wrote:

Code: Select all

c = ((b and 3) * 8) or (a and 7)
Or, if you prefer, use a shift operation.

Code: Select all

c = Shl(b And 3, 3) Or (a And 7)
The compiler probably generates the same code in either case.
- Don Kinzer
twesthoff
Posts: 247
Joined: 17 March 2006, 6:45 AM
Location: Fredericksburg, VA

exchange position bit

Post by twesthoff »

This should work too, same as above, but in several steps:

dim a as byte
dim b as byte
dim c as byte

a = &b0001_1101         ' (a7....a0) decimal=29
b = &b1000_1100         ' (b7....b0) decimal=140

Debug.Print "a = "; a, "b = "; b

'eg I need to exchange these bits
'c=000b1 b0a2a1a0 =0000 0101 ´decimal=5

a = a and &b0000_0111   'Mask 3 lower a-bits
b = b and &b0000_0011   'Mask 2 lower b-bits
b = b * &b0000_1000     'Adjust position of b-bits
c = a + b               'Combine into new c-bits

debug.print "c = ";c

ZBasic wrote:
I need to read individual bits in a byte and put some of those bits in a byte in different positions. you can help me , thanks
for example:

dim a as byte

dim b as byte

dim c as byte

a=bx 0001 1101 ' (a7....a0) decimal=29
b=bx 1000 1100 ' (b7....b0) decimal=140

eg I need to exchange these bits

c=000b1 b0a2a1a0 =0000 0101 ´decimal=5



Post Reply