从int转换为unsigned short

时间:2022-04-06 05:37:37

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

这是我不理解的C程序的一部分:

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 * but i didn't find the answer about this ! Thanks in advance :)

我的问题是如何找到一个大于64的int,但是当它转换为unsigned short时,它将小于64!我看了很多关于这些类型的整数的限制,即使在*,但我没有找到关于此的答案!提前致谢 :)

1 个解决方案

#1


4  

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

将int值分配给unsigned short时,将发生截断。

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.

假设int是4个字节而short是2,则只需要为程序提供一个大于64的值,其低两个字节小于64。

The maximum unsigned 16-bit value is 65535:

最大无符号16位值为65535:

0x0000FFFF

So if you enter the number 65536:

所以如果输入数字65536:

0x00010000

When truncated to just two bytes:

截断到只有两个字节时:

0x0000

Is zero.

是零。

#1


4  

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

将int值分配给unsigned short时,将发生截断。

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.

假设int是4个字节而short是2,则只需要为程序提供一个大于64的值,其低两个字节小于64。

The maximum unsigned 16-bit value is 65535:

最大无符号16位值为65535:

0x0000FFFF

So if you enter the number 65536:

所以如果输入数字65536:

0x00010000

When truncated to just two bytes:

截断到只有两个字节时:

0x0000

Is zero.

是零。