如何找到unsigned long long中的字符数

时间:2013-12-30 23:08:18

标签: c string-length unsigned-long-long-int

嗨我有2个问题,第一个是标题中的一个,另一个是在这里: unsigned long long是最大整数(可以容纳最大字符数)吗? 因为我需要一个可以容纳几百万字符(数字)的int这可能吗?我在C编码 这是我连接到另一个问题如何在屏幕上显示数字位数?它需要像这样吗?:

printf("%d", intName.length)

感谢每一个人!!

4 个答案:

答案 0 :(得分:1)

我假设当你提到字符数时你指的是数字中的位数。如果是这样,那么一个this question包含您需要知道的所有内容,并包含与此类似的代码

int numberOfDigits(unsigned long long n) 
{
    if (n == 0)
        return 0;
    return floor( log10( abs( n ) ) ) + 1;
}

至于持有几百万个数字,您可能希望使用包含函数的The GNU Multiple Precision Arithmetic Library等库来查看

size_t mpz_sizeinbase( const mpz_t op, int base )

会告诉你你的号码有多少位数。

答案 1 :(得分:0)

printf("%llu", xxxxxxxxx);

 the ll (el-el) long-long modifier with the u (unsigned) conversion

您也可以使用

 uint64_t a;
 uint32_t b;

但是你需要包含inttypes.h库,它为你提供类型,如int32_t,int64_t,uint64_t。

答案 2 :(得分:0)

C99提供intmax_t(和uintmax_t),它将是支持的最大整数类型(通常为64位)。

假设您有一个符合C99的snprintf,那么您可以使用以下符号获取位数:

length = snprintf(NULL, 0, "%llu", value);

表示无符号长long值(和%ju表示uintmax_t。)

否则你必须在(yuk)中传递缓冲区或手动执行某些操作,如:

length = value < 10 ? 1 :
         value < 100 ? 2 :
         ...

也是yuk!

但如果你真的想要百万位整数,那么这就完全无关紧要了,在这种情况下你需要使用像gmp这样的库来处理这么大的数字。

答案 3 :(得分:0)

给定类型的位长bitlen的无符号整数的最大十进制长度由1 + floor(log10(2^bitlen-1))给出(数学上,不考虑溢出和舍入误差)。近似值1/log2(10) ~ 4004.0/13301(通过连续分数获得,参见http://en.wikipedia.org/wiki/Continued_fraction)导致公式1 + bitlen * 4004 / 13301(计算上,即分割向下舍入)。数学细节在下面的片段的评论中给出。

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

/**
 * Maximal number of digits in the decimal representation of an unsigned type.
 *
 * floor( log2(2^bitlen - 1) / log2(10) ) == floor( bitlen / log2(10) )
 * otherwise an integer n would exist with
 *     log2(2^bitlen - 1) / log2(10) < n < bitlen / log2(10)
 *     log2(2^bitlen - 1) < n * log2(10) < bitlen
 *     2^bitlen - 1 < 2^(n * log2(10)) < 2^bitlen
 *     2^bitlen - 1 < (2^log2(10))^n < 2^bitlen
 *     2^bitlen - 1 < 10^n < 2^bitlen
 *     which is impossible
 *
 * 1 / log2(10) ~ 0.301029995663981
 * 4004 / 13301 ~ 0.30102999774453
 *
 *     1 + floor( log10(2^bitlen - 1) )
 *  == 1 + floor( log2(2^bitlen - 1) / log2(10) )
 *  == 1 + floor( bitlen / log2(10) )
 *  <= 1 + floor( bitlen * 4004.0 / 13301 )
 *  == 1 + bitlen * 4004 / 13301
 * with equality for bitlen <= 13300 == 8 * 1662.5
 */
#define DECLEN(unsigned_t) (1 + CHAR_BIT*sizeof(unsigned_t) * 4004 / 13301)

int main(int argc, char *argv[]) {
    printf("unsigned char      : %zu\n", DECLEN(unsigned char));
    printf("short unsigned     : %zu\n", DECLEN(short unsigned));
    printf("unsigned           : %zu\n", DECLEN(unsigned));
    printf("long unsigned      : %zu\n", DECLEN(long unsigned));
    printf("long long unsigned : %zu\n", DECLEN(long long unsigned));
    return 0;
}