简体   繁体   English

4字节char数组为整数,将在C的case语句中使用

[英]4 byte char array to an integer to be used in `case` statement in C

How can I use a char array with length 4 which is a string literal) to represent a 4 byte integer? 如何使用长度为4(是字符串文字)的char数组表示4个字节的整数?

I want to use a string literal with length 4 to substitute a 4 byte integer, which is to be used in this case statement. 我想使用长度为4的字符串文字来替换4字节整数,该整数将在本案例中使用。 I want to write like: 我想这样写:

case "\x0ATst":
    printf("FOUND TIME STAMP");
    break;

not: 不:

case 0x7473540A:
    printf("FOUND TIME STAMP");
    break;

As the primary code is more human readable. 由于主要代码更易于阅读。

I searched for "string to int" on google, but only answers like atoi() were found. 我在Google上搜索了“从int转换为int的字符串”,但只找到了atoi()类的答案。

switch only works with integer constants, so it isn't very flexible at all. switch仅适用于整数常量,因此根本不够灵活。 You can't use case with expressions, strings nor with any other type than int . 您不能将case与表达式,字符串或int以外的任何其他类型一起使用。

But in this case it doesn't matter, because you should have neither form, because neither of them is very readable. 但是在这种情况下,这并不重要,因为您都不应该使用任何形式,因为它们都不易读。 Instead use case STAMP: , where STAMP is some suitable, self-explaining name. 而是使用用case STAMP:其中STAMP是一些合适的自解释名称。 It could be a #define , const or enum . 它可以是# #defineconstenum

As for how to convert from a 4 character string to an int , there's various reasons why you can't simply do *(int*)"\\x0ATst" (alignment, strict aliasing). 至于如何将4字符串转换为int ,有多种原因导致您不能简单地执行*(int*)"\\x0ATst" (对齐,严格别名)。 There's a work-around for that, by using a union: 有一种解决方法,可以使用联合:

typedef union
{
  char str[4];
  unsigned int val;
} conv_t;

...

(conv_t){.str = "\x0ATst" }.val

Please note that this code depends heavily on CPU endianess, so it is still not very good practice. 请注意,此代码在很大程度上取决于CPU的耐久性,因此它仍然不是很好的做法。

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

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