|
-
August 4th, 2006, 03:27 AM
#1
Convert from unsigned short to double and back again
When you try to convert a number from double to unsigned short there is a possible loss of data, as this warning tell:
conversion from 'double' to 'unsigned short', possible loss of data.
But is this a danger in this case, when I first convert it from unsigned short to double?
Like this example:
Code:
unsigned short x = 10;
double y = x;
unsigned short z = y;
What I mean, is there any chance that z will hold anything else than 10 here?
Thanks!
Last edited by laitinen; August 4th, 2006 at 03:29 AM.
-
August 4th, 2006, 03:48 AM
#2
Re: Convert from unsigned short to double and back again
No. But the compiler can't know what your 'y' variable holds '10' and not '10.55', so the warning is issued.
-
August 4th, 2006, 03:58 AM
#3
Re: Convert from unsigned short to double and back again
-
August 4th, 2006, 05:02 AM
#4
Re: Convert from unsigned short to double and back again
Is there also the possiblilty that the double will see it as 9.99999999999 and therefore when you convert from the double to int you'll get z = 9. The safest bet here would be to round your answer first and remove the warning with an explicit cast.
-
August 4th, 2006, 05:42 AM
#5
Re: Convert from unsigned short to double and back again
thanks *io*!
Can you show how you do that rounding and casting stuff?
-
August 4th, 2006, 05:55 AM
#6
Re: Convert from unsigned short to double and back again
If you presume your number will always be positive then
Code:
unsigned short x = 10;
double y = x;
unsigned short z = (unsigned short)(y+0.5);
you should probably check that y isn't to big for a short but if you know it will never be then theres probably no need if it originates from a short anyway.
-
August 4th, 2006, 06:12 AM
#7
Re: Convert from unsigned short to double and back again
Is there also the possiblilty that the double will see it as 9.99999999999
Nope, there is no such posibility, because any integral number (such as 10) is the exact sum of some powers of 2. The problem of inaccuracy comes from the fact that some decimal values cannot be represented as a sum of inverted powers of 2. Can read more here.
-
August 4th, 2006, 06:33 AM
#8
Re: Convert from unsigned short to double and back again
Good point. I stand corrected.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|