Calculation of the maximum size of a signed integer

I wanted to know what my maximum value could have time_t, so I wrote a small program to help me. He needs one argument: the number of bytes (1 byte = 8 bits). So I wrote it and tested it. It works great for all values ​​from 1 to 4, but in 5 and above it also edits the "signed" bit (I don't know what it's called). Can someone explain:

#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;
}

My testing:

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

I hope to learn from this, so I would really appreciate it if someone takes the time to take a look at this.

ief2

+3
source share
1 answer

You use only int, namely 1, for the switching operation. it

someInt |= 1LL << i;

, .

, , , typedef, undefined, . , << .

time_t , . , , .

, ( ),

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

.

+1

Source: https://habr.com/ru/post/1788819/


All Articles