3

自分time_tが保持できる最大値を知りたかったので、簡単なプログラムを書きました。1 つの引数が必要です: バイト数 (1 バイト = 8 ビット)。だから私はそれを書いてテストしました。1 から 4 までのすべての値でうまくいきますが、5 以上では "signed" ビットも編集します (どのように呼び出されるかはわかりません)。誰かが説明できますか:

#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

4

1 に答える 1

1

シフト操作にintは、、つまり、のみを使用しています。1これ

someInt |= 1LL << i;

うまくいくと思います。

一般に、未定義の動作やコンパイラおよびプラットフォーム固有のプロパティのリスクを冒さずに、typedefのみを持つ符号付き整数型の最大値を取得する方法はありません。たとえば、<<演算子は符号付き型で問題が発生する可能性があります。

time_t浮動小数点型または整数型である可能性があるため、特に奇妙です。また、整数の場合、符号付きかどうかは指定されません。

符号付き整数型であり、いわゆるパディングビットがない場合(ほとんどのプラットフォームはそれに準拠しています)、最大値を直接計算できます。

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

オーバーフローすることなく。

于 2011-01-30T16:25:04.550 に答える