Created
October 13, 2011 04:10
-
-
Save shihongzhi/1283344 to your computer and use it in GitHub Desktop.
doutble2int
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//http://blog.codingnow.com/2006/02/double_to_int_magic_number.html | |
//http://www.cnblogs.com/Xiao_bird/archive/2010/03/26/1696908.html %f--8bytes %lf--8bytes %d--4bytes | |
#include <stdio.h> | |
union luai_Cast { double l_d; long l_l; }; | |
#define lua_number2int(i,d) { volatile union luai_Cast u; \ | |
u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; } | |
int main() | |
{ | |
printf("double size: %d;long size:%d; int size:%d\n",sizeof(double),sizeof(long), sizeof(int)); | |
double d = 1234567890.4; | |
int i; | |
lua_number2int(i,d); | |
printf("input: %f\noutput:%d\n\n",d,i); | |
d = 1234567890.5; | |
lua_number2int(i,d); | |
printf("input: %f\noutput:%d\n\n",d,i); | |
d = 1234567890.6; | |
lua_number2int(i,d); | |
printf("input: %f\noutput:%d\n\n",d,i); | |
// d = 2^31-1; | |
d = 2147483647.0; | |
lua_number2int(i,d); | |
printf("input: %f\noutput:%d\n\n",d,i); | |
// d = 2^31; | |
d = 2147483648.0; | |
lua_number2int(i,d); | |
printf("input: %f\noutput:%d\n\n",d,i); | |
d = 1234567890123.0; | |
lua_number2int(i,d); | |
printf("input: %f\noutput:%d\n\n",d,i); | |
getchar(); | |
return 0; | |
} | |
output: | |
double size: 8;long size:4; int size:4 | |
input: 1234567890.400000 | |
output:1234567890 | |
input: 1234567890.500000 | |
output:1234567890 | |
input: 1234567890.600000 | |
output:1234567891 | |
input: 2147483647.000000 //此宏只适合处理小于2^31的double,如果大于2^31,则会出错,即之后两个处理都出错了 | |
output:2147483647 | |
input: 2147483648.000000 | |
output:-2147483648 | |
input: 1234567890123.000000 | |
output:1912276171 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment