UP | HOME

Packing two bytes into an integer

I'm working on a 40% keyboard which has a 12x4 layout, and the firmware for now just need to support one key at a time.

The key scanning function returning a single integer, so I need to pack the two values Column and Row of a pressed key into this integer.

Since both of the column and row values are quite small (less than 255), I can just use two bytes to represent them. Therefore, I can pack them into an integer easily by using bit shift operators. Put the row value to the 8 low bits, and the rest is for the column value.

RESULT: int = (COL << 0) | (ROW << 8)

Later on in key sending logic, I can extract them all by shifting it back again:

COL: byte = (RESULT >> 0)
ROW: byte = (RESULT >> 8)

Date: 2019-01-29 Tue 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:40