Number of bits in a data type

后端 未结 6 1871
半阙折子戏
半阙折子戏 2021-02-06 14:53

I have two tasks for an assignment, one return the number of bits in type int on any machine. I thought I would write my function like so:

int CountIntBitsF() {         


        
6条回答
  •  粉色の甜心
    2021-02-06 15:43

    With g++ -O2 this function evaluates to an inline constant:

    #include 
    #include 
    #include 
    #include 
    
    template 
    size_t num_bits()
    {
        return sizeof (T) * (CHAR_BIT);
    }
    
    int main()
    {
        printf("uint8_t : %d\n", num_bits());
        printf("size_t : %d\n", num_bits());
        printf("long long : %d\n", num_bits());
        printf("void* : %d\n", num_bits());
        printf("bool : %d\n", num_bits());
        printf("float : %d\n", num_bits());
        printf("double : %d\n", num_bits());
        printf("long double : %d\n", num_bits());
    
        return 0;
    }
    

    outputs:

    uint8_t : 8
    size_t : 32
    long long : 64
    void* : 32
    bool : 8
    float : 32
    double : 64
    long double : 96
    

    Generated X86 32-bit assember:

    ---SNIP---

    movl    $32, 8(%esp)      <--- const $32
    movl    $.LC1, 4(%esp)
    movl    $1, (%esp)
    call    __printf_chk
    movl    $64, 8(%esp)      <--- const $64
    movl    $.LC2, 4(%esp)
    movl    $1, (%esp)
    call    __printf_chk
    

    ---SNIP---

提交回复
热议问题