Monday, November 22, 2010

Bit Packing

Last night I was busy hacking toll ticket, the application will be installed on a device that will be used for reading ticket when the power goes down. The problem is I must not using our ticket format for it, yeah in the name of vandalism. This word is very famous here. So we choose open Mifare Classic 1K card for that, open means with the standard transport key configuration.

The card need to hold some informations, the most important thing are shift (SH) and period (PR), vehicle classification (VC), plaza where the vehicle in (PI), post (PS), vehicle's direction (DR). We defined that maximum value for each information below all in integer type.

SH -> 0 - 3, 11 (2 bit), 11 or 0x3 as bitmask
PR -> 0 - 99, 1100011 (7 bit), 1111111 or 0x7f as bitmask
VC -> 0 - 5, 101 (3 bit), 111 or 0x7 as bitmask
PI -> 0 - 99, 1100011 (7 bit), 1111111 or 0x7f as bitmask
PS -> 0 - 99, 1100011 (7 bit), 1111111 or 0x7f as bitmask
DR -> 0 - 3, 11 (2 bit), 11 or 0x3 as bitmask


We have 28 bit, to construct them as integer we use the following as we already know

(SH & 0x3) << 26 | (PR & 0x7f) << 19 | (VC & 0x7) << 16 | (PI & 0x7f) << 9 | (PS & 0x7f) << 2 | (DR & 0x3)

For extracting those integers we use

SH = value >> 26 & 0x3
PR = value >> 19 & 0x7f
VC = value >> 16 & 0x3
PI = value >> 9 & 0x7f
PS = value >> 2 & 0x7f
DR = value & 0x3


This is only a simple bit operation that sometime we forgot how they are works, so here the source code, it need ACR120 communication library to be compiled.