12.6. Merging Scalar Variables

Problem

Scalar variables with constant or initialized values disclose information about ranges of values.

Solution

Merging multiple scalar values into a single, larger scalar value can make simple, unrelated values appear to be a large value or bit field. Two 8-bit values can be merged into a single 16-bit value, and two 16-bit values can be merged into a single 32-bit value.

Discussion

Merging scalar variables is a light obfuscation. When used in a loop, a debugger can set a watch on the counter variable and make obvious the fact that the upper or lower half of the variable is being incremented with each iteration of the loop.

The following macros merge two char values into a single short value, and two short values into a single int value. This is accomplished by shifting the shorter values into the larger value that contains them, and by masking half of the larger value and shifting as appropriate to retrieve the shorter value.

/* x and y are chars, returns a short */ /* x is in position 0, y is in position 1 */ #define MERGE_CHAR(x, y) (((y) << 8 ) | (x)) /* s is a short and c is position -- 0 or 1 */ #define GET_CHAR(s, c) (char)(((s) >> (8 * (c))) & 0x00FF) /* s is a short, c is a position, and val is a char value */ #define SET_CHAR(s, c, val) (((s) & (0xFF00 >> (8 * (c)))) | ((val) << (8 * (c)))) /* x and y are shorts. returns an int */ /* x is in position 0, y is in position 1 */ #define MERGE_SHORT(x, y) (((y) << 16 ) | (x)) /* i is an int and ...

Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.