【问题标题】:Calculating the maximum size of a signed integer计算有符号整数的最大大小
【发布时间】:2011-06-18 03:24:27
【问题描述】:

我想知道我的time_t可以容纳的最大值是多少,所以我写了一个小程序来帮助我。它需要一个参数:字节数(1 字节 = 8 位)。所以我写了它并测试了它。它适用于从 1 到 4 的所有值,但在 5 或更高时,它还会编辑“有符号”位(我不知道它是如何调用的)。谁能解释一下:

#include <stdio.h>

int main(int argc, const char **argv) {
    if(argc != 2) {
    fprintf(stderr, "Usage: %s bits/8\n", argv[0]);
    return -1;
    }

    unsigned int bytes;
    sscanf(argv[1], "%u", &bytes);

    unsigned int i;
    signed long long someInt = 0;
    size_t max = bytes*8-1;
    for(i = 0; i < max; i++) {
    someInt |= 1 << i;
    }

    /* Print all bits, we substracted 
    1 to use in the previous loop so 
    now we add one again */
    max++;
    for(i = 0; i < max; i++) {
    int isAct = (someInt >> max-i-1) & 1;
    printf("%d", isAct);
    if((i+1) % 8 == 0) {
        printf(" ");
    }
    }
    printf("\n");

    printf("Maximum size of a number with %u bytes of 8 btis: %lld\n", bytes, (long long)someInt);

    return 0;
}

我的测试:

Script started on Sun Jan 30 16:34:38 2011
bash-3.2$ ./a.out 1
01111111 
Maximum size of a number with 1 bytes of 8 btis: 127
bash-3.2$ ./a.out 2
01111111 11111111 
Maximum size of a number with 2 bytes of 8 btis: 32767
bash-3.2$ ./a.out 4
01111111 11111111 11111111 11111111 
Maximum size of a number with 4 bytes of 8 btis: 2147483647
bash-3.2$ ./a.out 5
11111111 11111111 11111111 11111111 11111111 
Maximum size of a number with 5 bytes of 8 btis: -1
bash-3.2$ ./a.out 8
11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 
Maximum size of a number with 8 bytes of 8 btis: -1
bash-3.2$ exit
exit

Script done on Sun Jan 30 16:35:06 2011

我希望从这个中学习,所以如果有人能抽出时间来看看这个,我真的很感激。

ief2

【问题讨论】:

    标签: c byte max bits signed


    【解决方案1】:

    您只使用int,即1,进行轮班操作。这个

    someInt |= 1LL << i;
    

    我认为会做得更好。

    一般来说,我不知道有一个有符号整数类型的最大值,你只有一个 typedef,而不会冒未定义的行为或编译器和平台特定属性的风险。例如,&lt;&lt; 运算符可能在有符号类型上存在问题。

    time_t 特别奇怪,因为它可能是浮点类型或整数类型。如果它是一个整数,则不指定它是否有符号。

    如果你认为它是一个有符号整数类型并且你没有所谓的填充位(大多数平台都符合),那么最大值可以直接计算

    ((((1LL << (sizeof(time_t)*CHAR_BIT-2)) - 1) << 1) + 1)
    

    没有溢出。

    【讨论】:

    • 非常感谢,将LL 添加到我的整数常量确实解决了我的问题。 time_t 在我的 Mac OS X 平台上定义为 /usr/include/i386/_types.h:typedef long __darwin_time_t;。我不知道填充位是什么,但无论如何我的可执行文件现在可以工作了。
    • 1LL(time_t)1 会更好。即使time_t 大于long long(扩展整数类型),它也可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多