"Partho" <pa**************@gmail.com> writes:
I tried this:
since a float is a 32 bit number, and is of the form 1.15, for ex., the
simplest technique is to scale the float by 2^15, and then type cast to
short:
short s = (short) (f * 2^15);
this puts the lower 16 bits of the float into the short var.
correct me if I am wrong.
Please don't top-post. See <http://www.caliburn.nl/topposting.html>.
Yes, you're wrong. For starters, "^" is the bitwise xor operator in
C; 2^15 is 13, not 32767. C has no exponentiation operator. (One way
to represent 2**15 is 1<<15; I'm using "**" here as an exponentiation
operator, though it doesn't exist in C.)
Your original question was:
| I have a float variable which I need to add to a short variable. How do
| I do this? Do I have to typecast or is there a way around? I tried
| typecasting the float to a short, but that gives me a 0 or +/-1, which
| is unacceptable.
What exactly do you mean by "of the form 1.15"?
This business about scaling by 2**15 is either new information that
you should have told us about in the first place, or a considerable
misunderstanding on your part.
Based on your original question, we assumed that, for example, you had
a short variable with a value of 5, and a float variable with a value
of 10.0, and you wanted to add them to yield a short value of 15 (or
whatever actual values you happen to have). If so, don't worry about
how the float is represented internally; it's just a number. A cast
(an explicit conversion) on a number merely converts the number to
another type with the same value (with truncation in the case of
floating-to-integer).
If at all possible, show us some actual code that illustrates your
problem, ideally a small, complete, self-contained program that we can
compile and run ourselves. Have it display the actual values of your
short and float variables (use printf with "%d" for short, "%g" for
float).
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.