Home > OS >  why itoa fuction returns 32 bits if the size of variable in 16 bit
why itoa fuction returns 32 bits if the size of variable in 16 bit

Time:09-19

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);

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

Output

11111111111111111111111111111110 2

CodePudding user response:

your problem is so simple , refer to itoa() manual , you will notice its prototype which is

char * itoa(int n, char * buffer, int radix);

so it takes an int that to be converted and you are passing a short int so it's converted from 2 byte width to 4 byte width , that's why it's printing a 32 bits.

to solve this problem : you can simply shift left the array by 16 position by the following simple for loop :

for (int i = 0; i < 17;   i) {
    buffer[i] = buffer[i 16];
}

and it shall give the same result , here is edited version of your code:

#include<stdio.h>
#include <stdlib.h>

int main(){
    char buffer [50];
    short int a= -2;
    itoa(a,buffer,2);

    for (int i = 0; i < 17;   i) {
        buffer[i] = buffer[i 16];
    }

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

and this is the output:

1111111111111110 2

CodePudding user response:

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( "X  X\n", -2, (unsigned short)(-2));

    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 );
  • Related