Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert int to short in C

Tags:

c

int

short

I have:

int a = 2147483647;
short b = (short)a;

and I get b = -1 whereas I expect int32 to be converted to int16(short). I expect to see some value and not -1.

Please someone help me with this.

like image 388
user1128265 Avatar asked Aug 16 '13 14:08

user1128265


People also ask

How do you convert int to short?

Integer shortValue() Method in Java lang which returns the value of this Integer in the short type . Parameters: The method does not take any parameters. Return Value: The method returns the integer value represented by this object after converting it to type short.

Can an int be a short?

short or short int Both data types are same, short int can also be written as short; short occupies 2 bytes in the memory.

How do you convert short to int in C++?

short a=2000; int b; b=a; Here, the value of a is promoted from short to int without the need of any explicit operator. This is known as a standard conversion.

Can we convert int to double in C?

The %d format specifier expects an int argument, but you're passing a double . Using the wrong format specifier invokes undefined behavior. To print a double , use %f .


2 Answers

This is implementation defined behavior, for example gcc Integers Implementation document says:

For conversion to a type of width N, the value is reduced modulo 2^N to be within range of the type; no signal is raised.

This can differ from compiler to compiler, I am not able to dig up similar documents for clang nor visual studio.

From the draft C++ standard, section 4.7 Integral conversions paragraph 3:

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

If this was unsigned then you would have perfectly well defined behavior, as per paragraph 2:

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

The language is similar in the C99 draft standard section 6.3.1.3 Signed and unsigned integers.

like image 79
Shafik Yaghmour Avatar answered Oct 28 '22 17:10

Shafik Yaghmour


Your int A is larger than the size of short. When you convert A to short, you get a 1 in the left most bit, which is going to indicate that it is a negative number. Since you're getting -1, I suppose you're getting 1s in all 16 bits, which is going to give you -2^15 + 2^14 + 2^13... + 2^0, which will give you -1. In short (no pun intended), you can't convert the integer to a short if it is too large.

like image 35
Magn3s1um Avatar answered Oct 28 '22 15:10

Magn3s1um