Basic arithmetic type conversion rule

Dear Sires:

I post the mail in borland forum and get following result about bit

conversion. I'm not sure I did get the correct answer, thus I re-post it

into the board. Can someone help me to identify the result.

Quote:

> Dear sir:

> I know the final result will be located between 0x00 to 0xFF (-127 to

> 128) if the variable is char type.

> But I don't know the rule how they made the result from -257 to any

> number between (-127 to 128)". By bitwise conversion or something else.

> For example:

> long int i = -32768; // long int means four byte precision.

> short int j = i; // short int means two byte

precision.

> short int k=-32768;

> Then what's the value of j and k after these expression ?

> For j, the value is passed from a high precision variable i.

> For k, the value is passed from a higher prevision constant value.

> Is there any difference ? And what's the general rules ?.

> > > Can somebody tell me the rules how C made type conversion from wide

> > > precision type

> > > to low precision type.

> > > For example:

> > > char a=-257; // "a" equal to "minus two hundred and fifty

seven".

> > The size of char types in BCB is one byte. This means it can only hold

> > values in the range [-128,127] if signed, or [0,255] if unsigned.

> > > The result will be "a" equal to "0x01". But how it made the

result?

> > > What's the rule ?

> > I would have expected it to become -1 if signed (0xff). I thought that

> > the bits 0--7 were retained and bits 8 and over were discarded.

> > However, if you really get +1 from -257, that must be wrong.

> > > >You are correct Mr. Radar User, bits 0-7 are kept. Remember, -257 is

> > > >actually needs 10 bits to represent it. I'm not too sure what the

> > > >"rules" are, but typically, what will happen is that the MSB (most

> > > >significant bits) are discarded.

> > > >In the -257 example:

> > > >-257 = 100000001 <- 9 bits, if we consider the sign, it would be

> > > >1100000001

> > > >Since char is only 8 bits, this number gets stored as: 0x00000001

which

> > > >is +1!

> > > >So, if long is 4 bytes:

> > > >i = -32768 = 10000000 00000000 10000000 00000000

> > > >Now, drop this into a short (2 bytes):

> > > >j = 10000000 00000000

> > > >or

> > > >k = 10000000 00000000

> > > >The value for j and k would be "-0" or 0. There are no real "rules"

> > > >that I know of; the convention has been to save the LSB's and discard

> > > >the rest.

> > > >Viggy