Reputation: 9349
I was goint through k & r. I was having problem in understanding following lines on page 197(section A6)
Integral conversions: any integer is converted to a given unsigned type by finding the smallest non negative value that is congruent to that integer,modulo one more than the largest value that can be represented in the unsigned type.
Can any body explain this in a bit detail. Thanks
Upvotes: 5
Views: 3167
Reputation: 111130
any integer is converted to a given unsigned type by finding the smallest non negative value that is congruent to that integer,modulo one more than the largest value that can be represented in the unsigned type.
Let's take this bit by bit and from backwards:
What is the largest value that can be represented in the unsigned type of width n bits?
2^(n) - 1.
What is one more than this value?
2^n.
How does the conversion take place?
unsigned_val = signed_val % 2^n
Now, the why part: The standard does not mandate what bit representation is used. Hence the jargon. In a two's complement representation -- which is by far the most commonly used -- this conversion does not change the bit pattern (unless there is a a truncation, of course).
Refer to Integral Conversions from the Standard for further details.
Upvotes: 6
Reputation: 421988
It means only low value bits will be count and high order bits will be discarded.
For example:
01111111 11111111 11110000 00001111
when converted to a 16 bit unsigned short
will be:
11110000 00001111
This is effectively mathematically expressed in:
target_value = value % (target_type_max+1) ( % = modulus operator )
Upvotes: 7