Packing two bytes into an integer

I’m working on building a 40% keyboard which has a 12×4 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)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website with
Get started
%d bloggers like this: