Search code examples
cbinarybitlow-level

Why itoa fuction returns 32 bits if the size of variable in 16 bit


Size of short int is 2 bytes (16 bits) on my 64 bit processor and mingw compiler but when I convert short int variable to a binary string using itoa function, it returns string of 32 bits:

#include<stdio.h>
int main(){
char buffer [50];
short int a=-2;
itoa(a,buffer,2); //converting a to binary

printf("%s %d",buffer,sizeof(a));
}

Output

11111111111111111111111111111110 2

Solution

  • The answer is in understanding C's promotion of short datatypes (and char's, too!) to int's when those values are used as parameters passed to a function and understanding the consequences of sign extension.

    This may be more understandable with a very simple example:

    #include <stdio.h>
    
    int main() {
    
        printf( "%08X  %08X\n", (unsigned)(-2), (unsigned short)(-2));
        // Both are cast to 'unsigned' to avoid UB
    
        return 0;
    }
    /* Prints:
    FFFFFFFE  0000FFFE
    */
    

    Both parameters to printf() were, as usual, promoted to 32 bit int's. The left hand value is -2 (decimal) in 32bit notation. By using the cast to specify the other parameter should not be subjected to sign extension, the printed value shows that it was treated as a 32 bit representation of the original 16 bit short.

    itoa() is not available in my compiler for testing, but this should give the expected results

    itoa( (unsigned short)a, buffer, 2 );