I’ve integrated a couple of devices recently that communicate via TCP/IP and have commands and responses that are built in binary hex strings. I did not see a built-in function that deals with this, but maybe I missed something.
It seems that the built-in NumberToHexString and HexStringToNumber commands (as well as the legacy NumberToFormattedHexString) are based on ascii strings, so that an ascii string “FF” converts to 255. However, in binary hex, “46 46” is what goes out the comm handle if that string is sent.
What I would like is to be able to convert 255 to the binary hex string “FF”, and vice versa. I think probably the (Transmit)ReceiveNumericTable(Ex) commands do this, but they require each element to be of the same size, and some message strings that I want to build or parse aren’t that nicely structured. They also communicate directly with the comm handle, which means the messages can’t be easily stored and handled in separate operations.
So, attached are a couple simple subroutines that do this for me, and a chart that demonstrates their usage. All of the subroutines are “additive” to whatever output variable is assigned. In other words, for the IntegerToHex routine, the new hex string will be appended onto the assigned string variable. For the HextoI32(64) routines, the new integer will be added to the assigned integer variable.
It is configured to use the PacSim control engine, but you might need to adjust it for your system. The “IntegerToHex” routine will handle I32 or I64 inputs, and will only give you the least significant bits if the receiving string isn’t big enough.
I couldn’t think of a way to make the hex to int conversion data type insensitive, so there are separate routines for HexToI32 and HexToI64.
The routines handle negative numbers correctly, and let you specify whether the byte sequence is big-endian or little-endian.
At some point, I may look at doing the same thing for floats, but I haven’t needed it so far.
In dealing with I64’s, I ran into a number of situations where constants need to be cast into 64 bits to keep the calculation at 64 bits. For example, the constant “8” would need to be “8i64”.
The attachment has been updated thanks to some suggestions Mary made below. The code is much cleaner than the original version.