简体   繁体   English

产生箭头键的输出

[英]producing output of arrow keys

As we know that arrow keys produces two outputs 224 and 77 or 80 or 72 or 75 . 众所周知,箭头键会产生两个输出22477807275

Code 1:- 代码1:-

int main()
{
    int ch,ch1;
    ch=getch();
    ch1=getch();
    printf("%d\n",ch);
    printf("%d",ch1);
}

When you press up key it displays 当您按up key它会显示

224
72

Code 2:- 代码2:-

int main()
{
    char ch,ch1;
    ch=getch();
    ch1=getch();
    printf("%d\n",ch);
    printf("%d",ch1);
}

When you press up key it displays 当您按up key它会显示

-32
 72

My question is that, as you can see that the second output is same for both char and int , but why the first output ie 224 and -32 are different with int and char . 我的问题是,正如您所看到的, charint的第二个输出都相同,但是为什么第一个输出(即224-32intchar不同。

Number 224, when stored in signed char , overflows. 当数字224存储在signed char ,溢出。

char typically gets considered as signed char and can hold values from -128 to 127 . char通常被认为是带signed char ,可以保存-128到127之间的值。 When you attempt to store a number beyond those limits, overflow occurs which causes the number to go around from the other end. 当您尝试存储超出这些限制的数字时,会发生溢出,从而导致数字从另一端四处走动。

You can think of it as filling a jar with water, then emptying out the whole jar when you fill the whole jar, and then go on filling whatever you are left. 您可以将其想象为是将一个罐子装满水,然后在装满整个罐子时清空整个罐子,然后继续装满剩下的东西。 In this case, you are filling a char variable with 224 ... So; 在这种情况下,您要用224 ...填充char变量。

  • 224 first fills 127, 224首填充127,
  • then you are left with 224 - 127 = 97, 那么您剩下224-127 = 97,
  • one more (97 - 1 = 96) and you are at -128 now, 还有一个(97-1 = 96),您现在是-128,
  • you end up at -128 + 96 = -32 您最终得到-128 + 96 = -32

这是因为char的范围是-128到127。这意味着您可以分配范围0到127的正值和-1到-128的负值。

The help/man page says that getch returns int: not char. 帮助/手册页上说getch返回int:不是char。

Depending on the compiler, char can default to either a signed char or an unsigned char. 根据编译器的不同,char可以默认为有符号字符或无符号字符。 The range for a signed char is -128..127, an unsigned char 0..255. 有符号字符的范围是-128..127,无符号字符0..255。 In this case, it is a signed char. 在这种情况下,它是一个签名的字符。 The Microsot compiler has a compiler switch for this. Microsot编译器为此提供了一个编译器开关。

If 224 is assigned to an unsigned char, you will get 224. If it is assigned to an unsigned char, you will get 224-256 = -32. 如果将224分配给一个未签名的字符,您将得到224。如果将它分配给一个未签名的字符,您将得到224-256 = -32。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM