Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Larger integer to smaller unsigned type conversion in C

Tags:

c

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

like image 393
mawia Avatar asked Apr 16 '09 11:04

mawia


People also ask

How do you convert a signed integer to an unsigned integer?

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.

What is implicit type conversion in C?

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.

What is unsigned integer underflow?

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.

How many types of conversion are there in C?

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion.


2 Answers

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 )
like image 57
mmx Avatar answered Nov 15 '22 04:11

mmx


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.

like image 34
dirkgently Avatar answered Nov 15 '22 02:11

dirkgently