Our full technical support staff does not monitor this forum. If you need assistance from a member of our staff, please submit your question from the Ask a Question page.


Log in or register to post/reply in the forum.

Hex to binary


Jbackwell May 26, 2018 09:20 AM

Hello all, I am using a CR1000X to read status messages from a sun tracker via RS485. The status message includes a hex value that represents the current operating mode of the tracker as well as a number of flags.

I'm able to read the messages via the serial bus, but I haven't been able to figure out a simple way to convert the Hex value into individual bits to be able to determine the state of the 'flags'. Any help would be appreciated!


JDavis May 29, 2018 03:35 PM

 This example should get you started. For this to work, the value must be loaded into a variable of type Long. If you have a hexadecimal string, you can use the HexToDec function to convert it to a number in a Long variable.

'Example of reading checking bit values with AND
Public LongVal As Long
Public Bits(32) As Boolean 'Array to represent bits, 1 based index
Public BinaryText As String * 32
Dim i As Long

'Main Program
BeginProg
  Scan (1,Sec,0,0)
    For i = 0 To 30 'Using a loop to check bit values
      Bits(i+1) = LongVal AND 2^i  'This does require processing time
    Next
    Bits(32) = IIF (LongVal < 0,True,False) 'Have to handle sign bit differently

    'Other method is one line of code for each bit to check
    'ex. Bits(4) = LongVal AND 8 'Faster than a loop

    BinaryText = ""
    For i = 32 To 1 Step -1 'Most significant bit first
      BinaryText = BinaryText & INT(Bits(i)*-1)
    Next
  NextScan
EndProg

 


Jbackwell May 29, 2018 04:26 PM

Thanks for your help, I'm looking forward to giving it a try.

I am very curious as to how it works - using AND just doesn't compute in my brain unfortunately!

Cheers,

Josh


JDavis May 30, 2018 11:13 AM

AND is a bitwise operator. The Long data type on a CR1000X is a 32 bit signed integer.

Knowing those pieces of information, you can read bits like in other programming languages. Understanding binary data formats is quite a lot to learn. It took me a while, without having a formal education in computer programming.

Log in or register to post/reply in the forum.