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
To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.
Overview. Implicit type conversion in C language is the conversion of one data type into another datatype by the compiler during the execution of the program. It is also called automatic type conversion.
Let's take a look at another example Unsigned int a,b; a=0 b=a-1 The value of b is -1 which is below than the minimum possible value that can be stored this is called an integer underflow.
There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion.
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 )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With