...
This produces the required output of 1.999999999E9. This is the value that is obtained when an int is assigned (implicitly cast) to a double.
Noncompliant Code Example
This noncompliant code example shows integer promotion when the bit-wise OR operator is used. The byte array element is sign extended to 32 bits before it is used as an operand. If it containd the value 0xff, now it would contain 0xffffffff.
| Code Block | ||
|---|---|---|
| ||
int result = 0;
for(int i = 0; i < 4; i++)
result = ((result << 8) | b[i]);
|
Compliant Solution
This compliant solution does not avoid integer promotion but works around it by masking off the upper 24 bits of the byte array element.
| Code Block | ||
|---|---|---|
| ||
int result = 0;
for(int i = 0; i < 4; i++)
result = ((result << 8) | (b[i] & 0xff));
|
Risk assessment
Failing to consider integer promotions when dealing with floating point and integer operands can result in loss of precision.
...