tags:

views:

178

answers:

2

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

+3  A: 

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 )
Mehrdad Afshari
+5  A: 

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.

dirkgently