简体   繁体   English

字符和字符不起作用的比较

[英]Comparison between char and char not working

I have made a (very bad) attempt at a crackme. 我曾尝试(非常糟糕)尝试破解。

This is the code: 这是代码:

#include <stdio.h>
#include <string.h>

int main()
{
    char passphrase[20];
    printf("Welcome to first_level.\n");
    printf("Hello. What's your passphrase?\n");

    fgets(passphrase,20,stdin);

    passphrase[strcspn(passphrase, "\n")] = 0;

    if(strlen(passphrase) != 10){
        // you lost
    } else
    {
        int counter = 0;
        for(int i = 0; i < 10; i++)
        {
            char index = i;
            char currentChar = passphrase[i];
            //printf(passphrase[i]);
            printf("---\nindex: %d\nchar: %c\n",index, currentChar);
            if(index == currentChar){
                //printf("ass\n");
                counter++;
            }
        }
        if(counter == 10)
        {
            printf("Congrats!\n");
            return 0;
        }

        printf("counter %d\n", counter);
    }

    printf("You lost!\n");
    return 0;
}

Now theoretically, the char comparison should work. 现在从理论上讲,字符比较应该起作用。 Unfortunately, I believe that the characters are converted to int, and then compared. 不幸的是,我相信这些字符会被转换为int,然后进行比较。

With the magical printf before the comparison I noticed that if I printed the number (%d), the char would be >48, while when printing the character (%c -- like the code provided), the character number is printed correctly. 在比较之前使用神奇的printf时,我注意到,如果我打印数字(%d),则char将大于48,而在打印字符(%c-类似于提供的代码)时,字符号会正确打印。

I am wondering how could I do this? 我想知道我该怎么做? I tried strcmp already but obviously it expects a string and not a char. 我已经尝试过strcmp但是显然它期望一个字符串而不是一个char。

The C Standard mandates that the characters '0' , '1' , ..., and '9' be sequential and consecutive. C标准要求字符'0''1' ,...和'9'必须连续且连续。 So we know the value of '1' is 1 greater than the value of '0' (and similarly for the other digits). 因此我们知道'1'的值比'0'的值大1(其他数字也类似)。

Taking the above into consideration, we know that 考虑到以上因素,我们知道

'0' - '0' == 0;
'1' - '0' == 1;
....
'9' - '0' == 9;

Note that all of the above must work as I described, whether running on an ASCII based computer, or EBCDIC, or Klingon, or whatever. 请注意,无论在基于ASCII的计算机,EBCDIC,Klingon或其他任何设备上运行,上述所有内容都必须按照我所描述的那样工作。

So, to compare digits in character form ( '0' , ..., '9' ) with integer values ( 0 , ..., 9 ) simply subtract '0' from the char. 因此,要将字符形式( '0' ,..., '9' )的数字与整数值( 0 ,..., 9 )比较,只需从char中减去'0'

if (index == currentChar - '0') /* ... */;

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

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