C-确定char、short、int、long、long long、float和double的范围

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

/*
 * Range.c - by FreeMan
 */

#include <stdio.h>
#include <limits.h>

float getFloat(char sign, unsigned char exp, unsigned mantissa);
double getDouble(char sign, unsigned short exp, unsigned long long mantissa);

int main(void)
{
	printf("Signed char [%d to %d]\n", 
		~((unsigned char)~0 >> 1), (unsigned char)~0 >> 1);
	printf("Unsigned char [0 to %u]\n", (unsigned char)~0);

	printf("Signed short [%d to %d]\n", 
		~((unsigned short)~0 >> 1), (unsigned short)~0 >> 1);
	printf("Unsigned short [0 to %u]\n", (unsigned short)~0);

	printf("Signed int [%d to %d]\n", ~(~0U >> 1), ~0U >> 1);
	printf("Unsigned int [0 to %u]\n", ~0U);

	printf("Signed long [%ld to %ld]\n", ~(~0UL >> 1), ~0UL >> 1);
	printf("Unsigned long [0 to %lu]\n", ~0UL);

	printf("Signed long long [%lld to %lld]\n", ~(~0ULL >> 1), ~0ULL >> 1);
	printf("Unsigned long long [0 to %llu]\n", ~0ULL);

	printf("Float [%g to %g]\n", getFloat(1, 0, 1), getFloat(0, ~0 - 1, ~0));

	printf("Double [%g to %g]\n", getDouble(1, 0, 1), getDouble(0, ~0 - 1, ~0));

	return 0;
}

float getFloat(char sign, unsigned char exp, unsigned mantissa)
{
	unsigned f = (unsigned)(sign != 0) << 31 | (unsigned)exp << 23 
		| mantissa & 0x7FFFFF;
	return *((float *)&f);
}

double getDouble(char sign, unsigned short exp, unsigned long long mantissa)
{
	unsigned long long d = (unsigned long long)(sign != 0) << 63 
		| (unsigned long long)(exp & 0x7FF) << 52 | mantissa & 0xFFFFFFFFFFFFF;
	return *((double *)&d);
}

// Output:
/*
Signed char [-128 to 127]
Unsigned char [0 to 255]
Signed short [-32768 to 32767]
Unsigned short [0 to 65535]
Signed int [-2147483648 to 2147483647]
Unsigned int [0 to 4294967295]
Signed long [-2147483648 to 2147483647]
Unsigned long [0 to 4294967295]
Signed long long [-9223372036854775808 to 9223372036854775807]
Unsigned long long [0 to 18446744073709551615]
Float [-1.4013e-45 to 3.40282e+38]
Double [-4.94066e-324 to 1.79769e+308]

*/

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页