FlexibleIntegerVariables

WinHex & X-Ways

Flexible Integer Variables

 

A special variable type supported by templates is uint_flex. This type allows to compose an unsigned integer value from various individual bits within a 32-bit (4-byte) range in an arbitrary order and is even more flexible than a so-called bit field in the C programming language.

 

uint_flex requires an additional parameter string in inverted commas that specifies exactly which bits are used in which order, separated by commas. The bit listed first becomes the most significant bit (high value bit) in the resulting integer, and it is not interpreted as a + or - indicator. The bit listed last becomes the least significant bit in the resulting integer.

 

The bits are counted starting with 0. Bit 0 is the bit that is the least significant bit of the 1st byte. Bit 31 is the most significant bit of the fourth byte. Thus, the definition is based on little-endian philosophy.

 

For example,

uint_flex "15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0" "Standard 16-bit integer"

is exactly the same as uint16, the common unsigned 16-bit integer variable.

 

uint_flex "31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0" "Standard 32-bit integer"

is exactly the same as uint32, the common unsigned 32-bit integer variable.

 

The benefit of uint_flex, though, is that the number, the position, and the usage order of all bits can be chosen arbitrarily. For example,

uint_flex "7,15,23,31" "An unusual 4-bit integer"

composes a 4-bit integer out of the respective most significant bits of each of the four bytes involved. If these four bytes happen to be F0 A0 0F 0A = 11110000 10100000 00001111 00001010, bit 7 is 1, bit 15 is 1, bit 23 is 0, and bit 31 is 0. So the resulting uint_flex is 1100 = 1*8 + 1*4 + 0*2 + 0*1 = 12.