Page 1 of 1

exchange position bit

Posted: 21 July 2009, 12:00 PM
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

exchange position bit

Posted: 21 July 2009, 12:26 PM
by GTBecker

Code: Select all

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

Tom

Re: exchange position bit

Posted: 21 July 2009, 12:37 PM
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.

exchange position bit

Posted: 21 July 2009, 12:39 PM
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