Gutanoth - 1 year ago 93
C Question

# Efficient concatenation

Currently I am trying to send a message over an LPWAN and one of the issues i am facing is trying to get my message as short as possible.

For example:

I have two integers (0-100) and two booleans wich I have to convert to a Hex to send over the LPWAN. Example:

• 24

• 63

• True

• False

When I concatenate this as 246310 (Hex:3C226), this will take 3 bytes. However, I know that my first integer will never be higher than 50, wich is just 6 bits. Is it possible for me to make the hex message shorter than 3C226?

Yes, that should be possible.

The number of bits for your fields are:

• `integer0`: Integer 0..50, 6 bits.
• `integer1`: Integer 0..80, 7 bits.
• `flag0`: Boolean, 1 bit.
• `flag1`: Boolean, 1 bit.

So that's a total of 6 + 7 + 1 + 1 = 15 bits.

Here's how to encode:

``````+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|15|14|13|12|11|10| 9| 8| 7| 6| 5| 4| 3| 2| 1| 0|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
|  |                 |                    |  |  |
|  |  integer0       |  integer1          |f0|f1|
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

uint16_t encode(uint8_t integer0, uint8_t integer1, bool flag0, bool flag1)
{
return ((uint16_t) integer0 << 9) | ((uint16_t) integer1 << 2) | ((uint16_t) flag0 << 1) | flag1;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download