MATLAB Examples

Packaging Protocol

Contents

Overview

The provided pack and unpack data functionality uses binary arrays to split up data into bytes. Underneath the functions, this packaging process is performed by the function typecast

In general, the process is as follows. Unsigned integers are broken up into bytes. Signed integers are packed using Two's Complement.

Unsigned Data

Unsigned data is split into bytes which represent sections of the data. A uint16 breaks down into two uint8 bytes. A uint32 breaks down into four uint8 bytes.

For instance, a uint16 with a value of 65535 when converted into binary is a 1x16 array of 1's:

binaryArray = dec2bin(65535,16)
binaryArray =

1111111111111111

When broken down into two 8-bit arrays, the two arrays are as follows:

binaryArray1 = binaryArray(1:8)
binaryArray2 = binaryArray(9:16)
binaryArray1 =

11111111


binaryArray2 =

11111111

These bits are represented with the MSB first. Consequently, a uint16 with a value of 1 when converted to 8-bit binary arrays is as follows:

binaryArray = dec2bin(1,16)
binaryArray1 = binaryArray(1:8)
binaryArray2 = binaryArray(9:16)
binaryArray =

0000000000000001


binaryArray1 =

00000000


binaryArray2 =

00000001

Converting the two 1x8 binary arrays of 1's from 65535 into uint8's and we get the following:

binaryArray = dec2bin(65535,16);
binaryArray1 = binaryArray(1:8);
binaryArray2 = binaryArray(9:16);
byte1 = bin2dec(binaryArray1)
byte2 = bin2dec(binaryArray2)
byte1 =

   255


byte2 =

   255

Checking the result with the packData function, we get the same bytes

packData(uint16(65535),'uint16',1)
ans =

  255  255

Signed Data

Two's Complement is used to package signed integer data. The steps are as follows:

  1. Take the absolute value and convert to a binary array
  2. Convert to a unsigned integer by adding a Most Significant Bit of 0
  3. Invert the bits in the binary array
  4. Convert the binary array into a uint8
  5. Add one to the uint8

Let's demonstrate this:

1. First, the positive part is converted to bits

in = -127;
positiveBits = uint8(dec2bin(abs(in)))-48
positiveBits =

    1    1    1    1    1    1    1

2. Then the binary array is converted to an unsigned integer. In this case, the uint7 is converted to a uint8.

uint8Bits = zeros(1,8);
uint8Bits(2:end) = positiveBits
uint8Bits =

     0     1     1     1     1     1     1     1

3. These bits are inverted

invertedBits = ~uint8Bits
invertedBits =

     1     0     0     0     0     0     0     0

4. The binary array is converted to a uint8

invertedByte = bin2dec(char(invertedBits+48))
invertedByte =

   128

5. 1 is added to this uint8 and output from the packData function

addOneByte = invertedByte + 1
addOneByte =

   129

Checking the result with the packData function, we get the same byte

out = packData(int8(-127),'int8',1)
out =

  129