Author Topic: Bit Shift  (Read 18452 times)

Lorne Van Dusen

  • Jr. Member
  • Posts: 93
  • I'm a old guy
    • View Profile
Bit Shift
« on: March 09, 2020, 11:35:58 AM »
I was reading the tbasic manual and came across the LSHIFT & the RSHIFT. The explanation shows and example of LSHIFT as being LSHIFT ,n The i is a DM[n] or RELAY[n] etc then you can add a , and a number equal to the number of channels that you want to shift. So if you want to shift Relay channels 2 to four you would LSHIFT RELAY[2] , 3 so far so good. However if I want to shift just RELAY[2] by one bit I would use LSHIFT RELAY[2]. My question is what is the simplest way to shift left by 2 bits. Do you have to do LSHIFT RELAY[2] then again LSHIFT RELAY[2]
example LSHIFT RELAY[2]
LTSHIFT RELAY[2]
OUTPUT[1] = RELAY[2]
I would have thought that there would be a way to enter the number of shifts such as LSHIFT RELAY[2] ,1 for number of channels and a second , and the number of shifts.   

Forum Admin

  • Administrator
  • Newbie
  • *****
  • Posts: 20
  • Let's control via the NET
    • View Profile
    • Internet Programmable PLCs
Re: Bit Shift
« Reply #1 on: March 09, 2020, 07:48:59 PM »
LSHIFT or RSHIFT only shift left or right by 1 bit. It doesn't support multiple bit shifting in a single command.

You can use a FOR NEXT loop and execute the number of time you want to shift the bit.

Another way is to multiply the channel with a number. E.g. x2 is to shift 1 bit to the left , x4 is to shift 2 bits to the left... x 256 is to shift by 8 bit to the left. You will probably need to mask out the overflow bit with an AND mask to prevent number from turning into negative.

support

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 3174
    • View Profile
    • Internet Programmable PLCs
Re: Bit Shift
« Reply #2 on: March 10, 2020, 02:00:10 PM »
Attached is a sample program for using the LSHIFT function for multiple bits.

A parameter X that contains the number of bits is passed to the function fnLShiftXBit which then uses a FOR NEXT loop to shift X bits to the left.

Note:
We cascaded two relay channels so that the single bit will shift across both RELAY[1] and RELAY[2] - total 32-bits. You can change the number of channels to 1 if you just want the shift to happen within RELAY[1] and not moving into the higher RELAY[n] channels.

Email: support@triplc.com
Tel: 1-877-TRI-PLCS

Lorne Van Dusen

  • Jr. Member
  • Posts: 93
  • I'm a old guy
    • View Profile
Re: Bit Shift
« Reply #3 on: March 16, 2020, 01:37:05 PM »
Your explanation was perfect and the solution was simple
In my custom function i just used X = ? and I change the ? to the number of shifts I needed
example
X = 4 'To shift 4 bits to the left
FOR I = 1 to X
LSHIFT RELAY[1] 'I only needed 1 channel
NEXT