Hey all, here's an old school trick using bit shifts to encode two or more numeric values (in this case three) into a single integer and decode them later. It's perfect when you need to keep or send two or more relatively small values and multiple variables or arrays are not a tenable option. You'd be surprised how often this happens.

As an example, one 32bit integer can accommodate three values of 0-255 each. Sound familiar? That's how color codes work, and in fact the native RGB() function will work as a decoding shortcut.

Here's some sample code that shows it in action. We take three numeric values with a range of 0-255 (8bit), encode them into to a single integer (32bit), decode them back to the original three values, and output to log. I'm using this for a cancel system, but there are hundreds of possible uses depending on your needs.

Output:

Enjoy!

DC

As an example, one 32bit integer can accommodate three values of 0-255 each. Sound familiar? That's how color codes work, and in fact the native RGB() function will work as a decoding shortcut.

Here's some sample code that shows it in action. We take three numeric values with a range of 0-255 (8bit), encode them into to a single integer (32bit), decode them back to the original three values, and output to log. I'm using this for a cancel system, but there are hundreds of possible uses depending on your needs.

C:

```
/* Masks and bit shift values. */
#define MASK 0xFF
#define SHIFT_B 8
#define SHIFT_C 16
/* Example values. */
int value_a = 14;
int value_b = 255;
int value_c = 12;
int value_encoded = 0;
/*
* Encode our three values into one integer.
*
* Either of these will work. The first is faster
* while the second allows you to set the
* encoded values piecemeal.
*/
// value_encoded = (value_a & MASK) | ((value_b & MASK) << SHIFT_B) | ((value_c & MASK) << SHIFT_C);
value_encoded += (value_a & MASK);
value_encoded += (value_b & MASK) << SHIFT_B;
value_encoded += (value_c & MASK) << SHIFT_C;
/* Decompress and output to log. */
log("\n value_encoded: " + value_encoded);
log("\n value_a: " + (value_encoded & MASK_A));
log("\n value_b: " + ((value_encoded >> SHIFT_B) & MASK_A));
log("\n value_c: " + ((value_encoded >> SHIFT_C) & MASK_A));
```

Output:

C:

```
value_encoded: 851726
value_a: 14
value_b: 255
value_c: 12
```

Enjoy!

DC

Last edited: