代码之家  ›  专栏  ›  技术社区  ›  Yanick Rochon

为x位分配n个字节

  •  1
  • Yanick Rochon  · 技术社区  · 15 年前

    首先,这可以是任何语言的通用算法,但是我正在学习C,如果有一些C特定的特性,我想知道!

    我正在编写一个函数,它将为给定的位数分配足够的内存;到 long long * 变量。位数不能是 < 1 . 我测试了算法:

    int bits;  // the function argument, checked for value > 0
    size_t dataSize;  // the value passed to the malloc function
    
    for (bits = 1; bits<100; bits++) {
       if (bits < sizeof(long long)) {
          dataSize = 1;
       } else {
          dataSize = (bits + (sizeof(long long) - (bits % sizeof(long long)))) / sizeof(long long);
       }
    
       printf("%d = %d\n", bits, (int) dataSize);
    }
    

    看起来不错…但丑:) 有什么方法可以更优雅地实现这一点? 谢谢您!

    8 回复  |  直到 15 年前
        1
  •  2
  •   Christoph    15 年前

    calloc() malloc()

    #include <limits.h>
    
    const size_t BITS_PER_BLOCK = sizeof (long long) * CHAR_BIT;
    size_t count = bits / BITS_PER_BLOCK + !!(bits % BITS_PER_BLOCK);
    unsigned long long *blocks = calloc(count, sizeof *blocks);
    

    !! 1 BITS_PER_BLOCK

    size_t count = (bits + BITS_PER_BLOCK - 1) / BITS_PER_BLOCK;
    

        2
  •  1
  •   user470379    15 年前

    int bits;
    size_t dataSize;
    
    dataSize = bits / (sizeof(long long) * 8);
    if( bits % (sizeof(long long) * 8) ) { //Don't add 1 if it was evenly divisible
        dataSize++;
    }
    dataSize *= sizeof(long long)
    

    long long

        3
  •  1
  •   Å imon Tóth    15 年前

    long long

    int bits = n;
    int items = (((bits - 1) / CHAR_BIT) / sizeof(long long)) + 1;
    
        4
  •  0
  •   MahlerFive    15 年前

        5
  •  0
  •   nategoose    15 年前
    size_t len_needed(int bits) {
       size_t x=  bits/(sizeof(long long) * 8);
       x = (bits%(sizeof(long long) * 8) ? 1 : 0;
    
       return x;
    }
    

    ? :

        6
  •  0
  •   pmg    15 年前

    int bits;  // the function argument, checked for value > 0
    size_t dataSize;  // the value passed to the malloc function
    
    for (bits = 1; bits<100; bits++) {
       if (bits < sizeof(long long)) {
          dataSize = 1;
       } else {
          dataSize = (bits + (sizeof(long long) - (bits % sizeof(long long)))) / sizeof(long long);
       }
    
       printf("%d = %d (%d)\n", bits, (int) dataSize, 1 + bits/sizeof (long long));
       /*             ^^^^^                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
    }
    
        7
  •  0
  •   MSN    15 年前
    Number_of_long_longs_for_x= (x + sizeof(long long) - 1)/sizeof(long long)
    

    long long log2(ULLONG_MAX+1) sizeof(long long)

        8
  •  0
  •   alvin    15 年前
    #define SIZEOF_LL  sizeof(long long)
    nbytes  =  (xbits  + 8         - 1) / 8;
    nllongs =  (nbytes + SIZEOF_LL - 1) / SIZEOF_LL;
    

    nbytes =  (xbits  + 7) / 8;
    nllongs = (nbytes + 7) / 8;