简体   繁体   English

C中三元运算符的逻辑?

[英]Logic of ternary operator in C?

I'm studying some AES implementation C code. 我正在研究一些AES实现C代码。 The encryption code needs to get the password passed as argument, and so the encrypted and the output file. 加密代码需要获取作为参数传递的密码,以及加密和输出文件。

I understand it reads the password and that also treats it and turns it into a key. 据我所知,它会读取密码并对其进行处理并将其转换为密钥。 But there's this cycle where I can't really understand what it's doing. 但是在这个循环中,我无法真正理解它在做什么。

int main(int argc, char **argv) {
 unsigned long rk[RKLENGTH(KEYBITS)];
 unsigned char key[KEYLENGTH(KEYBITS)];
 int i;
 int nrounds;
 char *password;
 FILE *output;
 if (argc < 3) {
  fputs("Missing argument\n", stderr);
  return 1;
 }                                              
 password = argv[1]
 for (i = 0; i < sizeof(key); i++)
  key[i] = *password != 0 ? *password++ : 0;  /* HERE IS WHERE I CAN'T GET IT */

What's exactly happening with the key string? 关键字符串到底发生了什么? I think there's some logical stuff and bits operations. 我认为有一些逻辑的东西和位操作。

The loop you are looking at is copying sizeof(key) bytes from the password string into the key buffer, and padding the rest of the buffer with 0 if the length of the password string is smaller than sizeof(key) . 您正在查看的循环是将password字符串中的sizeof(key)字节复制到key缓冲区中,如果password字符串的长度小于sizeof(key) ,则将缓冲区的其余部分填充为0

The ternary operator has the form: 三元运算符具有以下形式:

condition ? 条件 ? expression-1 : expression-2 表达式-1 : 表达式-2

If condition is true, then expression-1 is evaluated, otherwise expression-2 is evaluated. 如果condition为true,则计算expression-1 ,否则计算expression-2 There is short circuiting, in that only one of the expressions is ever evaluated. 存在短路,因为只评估了其中一个表达式。 So, in your code: 所以,在你的代码中:

    key[i] = *password != 0 ? *password++ : 0; 

Once *password != 0 becomes false, password does not get incremented again. 一旦*password != 0变为false, password就不会再次递增。

For each byte in the key, if there's a corresponding byte in the password (originally argv[1] ), copy that byte to the key; 对于密钥中的每个字节,如果密码中有相应的字节(最初为argv[1] ),则将该字节复制到密钥; else copy a 0 (byte) to the key. 否则将0(字节)复制到密钥。 It's a long-winded way of writing: 这是一种冗长的写作方式:

strncpy(key, password, sizeof(key));

(It is also one of the few times I'll ever recommend using strncpy() ; in general, it doesn't do what people expect, but here, it does exactly what is required.) (这也是我建议使用strncpy()的少数几次之一;一般情况下,它不会达到人们的期望,但在这里,它完全符合要求。)

Similarly : 同样:

 key[i] = *password != 0 ? *password++ : 0;  /* HERE IS WHERE I CAN'T GET IT */

 =

 if (*password != 0) { key[i]=*password++; } else { key[i]=0; } ;

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

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