posted:
Sorry if this is off-topic but can someone explain to me what a
"trapping bit" is ?
Cheers
Spiros Bousbouras
Take an unsigned 16-Bit integer:
0000 0000 0000 0000
Each bit has one of two possible values, one or zero. We have 16 of them.
The amount of unique combinations is: 65 536 (that's 2 to the power of
16).
If we use this unsigned 16-Bit integer to store a number, we can store
numbers in the following range:
0 to 65 535 inclusive.
However, it's possible to have a 18-Bit unsigned integer, except that
only 16 of the bits are used for value representation. The other two bits
are used for "trapping".
Trapping is where the system tests for an invalid value.
Here's our sample 18-Bit unsigned integer which has only 16-Bit value
representation bits:
00 0000 0000 0000 0000
The particular platform we're working on may decide that the trapping
bits must be 11 in order for the number to be valid. So when you do the
following:
unsigned k = 5;
Then it looks like so in memory:
11 0000 0000 0000 0101
Why have trapping bits? Because you can detect when a variable contains
garbage, as in the following:
int main(void) { unsigned k; }
"k" was never initialised, so all of its 18 bits can have any value.
Using trapping bits however, the system can detect whether it contains
garbage or a legitimate value.
It's usually only any use for debugging... and would only really work
properly if all relevent memory was set to zero before hand, because
there's a 1 in 4 chance that the trapping bits will be okay even when the
variable was never initialised.
The following is undefined behaviour because of the possibility of
trapping bits:
unsigned a;
unsigned b = a;
Thankfully though, we're guaranteed that "unsigned char" has no trapping
bits. Therefore, the following is okay:
unsigned char a;
unsigned char b = a;
And we can also safely access any sequence of memory as if it were an
array of unsigned chars. For example:
double array[45];
unsigned char *p = (unsigned char*)(array + 6);
unsigned char c = *p; /* No problem */
However, the following may cause Undefined Behaviour because of the
possibility of trapping bits:
double array[45];
unsigned int *p = (unsigned int*)(array + 6);
unsigned int k = *p; /* Bad idea! */
-Tomás