john john - 1 year ago 167
C Question

Conversion from int to unsigned short

this is a part of a C program that i didn't understand :

unsigned short twittlen;
int x;
x = atoi(argv[1]);
twittlen = x;
if(twittlen >= 64){
printf("Nope , You don't know about Integer");
return -1}
if (x >= 64 )
printf("you got it ");

My problem is how to find an int that is greater than 64 but when converting it to unsigned short it will be less than 64 !
I looked alot about limit of those types of integers even on stackoverflow but i didn't find the answer about this !
Thanks in advance :)

Answer Source

When you assign an int value to an unsigned short, truncation will occur.

Assuming int is 4 bytes and short is 2, you simply need to provide the program with a value greater than 64 whose lower two bytes are less than 64.

The maximum unsigned 16-bit value is 65535:


So if you enter the number 65536:


When truncated to just two bytes:


Is zero.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download