Author Topic: reversing bits  (Read 12688 times)

Lorne Van Dusen

  • Jr. Member
  • Posts: 93
  • I'm a old guy
    • View Profile
reversing bits
« on: May 25, 2017, 06:07:57 PM »
I did a search on the Internet for how to reverse bits and was surprised to find out how many times people have asked that question however most answers were for a C or C++
is there a simple way to reverse the bits in either a 8 bit or 16 bit value stored say in DM1 in TBASIC Fx series plc
example dm1 = 11100000 the result should be 00000111

support

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 3174
    • View Profile
    • Internet Programmable PLCs
Re:reversing bits
« Reply #1 on: May 26, 2017, 08:36:14 AM »
Below is a 16 bit reverse bit example.

A = &HF5A0  ' put any value you want in A

B = 0

FOR I = 0 to 15
   IF TESTBIT(A, 15-I)
      SETBIT B, I
   ELSE
      CLRBIT B, I
   ENDIF
NEXT

' Result: B = &H05AF if A=&HF5A0
« Last Edit: May 26, 2017, 08:37:05 AM by support »
Email: support@triplc.com
Tel: 1-877-TRI-PLCS

garysdickinson

  • Hero Member
  • Posts: 502
  • Old PLC Coder
    • View Profile
Re:reversing bits
« Reply #2 on: May 26, 2017, 08:47:51 AM »
You can eliminate the "else" clause in the "if" statement as all of the bits in B have been set to 0 outside the for loop:

B = 0

FOR I = 0 to 15
   IF TESTBIT(A, 15-I)
      SETBIT B, I
   ENDIF
NEXT


Gary D