Tag values - converting 16-bit integer to two 8-bit integers

I’m wondering if there is an easy way to convert a 16-bit integer tag value into two 8-bit tag values (one for the high byte, one for the low byte).

Here’s how i’ve been doing it:

  1. I have an integer value coming into an OPC tag.
  2. I make an expression tag that converts the integer into a binary string using the toBinary function. The toBinary function seems to strip leading zeros, so I also have some code to pad the binary string with zero’s to make it 16 bits long.
  3. I make 2 more expression tags. One tag reads the first 8 characters/bits of the binary string, the other reads the second 8 characters/bits. Now I have the high and low bytes of my original integer stored in 2 separate tags, as binary strings.
  4. I make 2 more expression tags. I use the fromBinary function to convert the two 8-bit binary strings into integers.

Anyone know of a more straight forward way to accomplish this?

Note: I know I can consolidate some of the expression tags, it’s just easier to explain my question this way.

Probably not even close to the best way, but run this script on value change:

import struct
a = 4634
s = struct.pack('>H', a)

first, second = struct.unpack('>BB', s)
print first
print second

I’m curious to know the need? Packing bits was a real need back in the PLC5 days, but today?

You guys are overthinking this.

High Byte: ({IntegerTag} >> 8) & 0xFF
Low Byte: {IntegerTag} & 0xFF


Wow haha… Thanks.

Is it possible to do that conversion in the original tag definition or do you have to pull it into a tag and then create an expression tag to do the conversion. It would be a lot cooler to do it all in one tag

You need a separate tag. The Modbus driver doesn’t have byte-level addressing because registers are 16-bit.