我需要根据 4 个字符的字符串进行切换。我将字符串放在 union 中,这样我至少可以将其作为 32 位整数引用。
union
{
int32u integer;
char string[4];
}software_version;
但是现在我不知道在case语句中写什么。我需要某种宏来将 4 个字符的字符串文字转换为整数。例如
#define STRING_TO_INTEGER(s) ?? What goes here ??
#define VERSION_2_3_7 STRING_TO_INTEGER("0237")
#define VERSION_2_4_1 STRING_TO_INTEGER("0241")
switch (array[i].software_version.integer)
{
case VERSION_2_3_7:
break;
case VERSION_2_4_1:
break;
}
有没有办法制作 STRING_TO_INTEGER() 宏。还是有更好的方法来处理切换?
最佳答案
可移植示例代码:
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#define CHARS_TO_U32(c1, c2, c3, c4) (((uint32_t)(uint8_t)(c1) | \
(uint32_t)(uint8_t)(c2) << 8 | (uint32_t)(uint8_t)(c3) << 16 | \
(uint32_t)(uint8_t)(c4) << 24))
static inline uint32_t string_to_u32(const char *string)
{
assert(strlen(string) >= 4);
return CHARS_TO_U32(string[0], string[1], string[2], string[3]);
}
#define VERSION_2_3_7 CHARS_TO_U32('0', '2', '3', '7')
#define VERSION_2_4_1 CHARS_TO_U32('0', '2', '4', '1')
int main(int argc, char *argv[])
{
assert(argc == 2);
switch(string_to_u32(argv[1]))
{
case VERSION_2_3_7:
case VERSION_2_4_1:
puts("supported version");
return 0;
default:
puts("unsupported version");
return 1;
}
}
该代码仅假定整数类型 uint8_t
和 uint32_t
的存在,并且与 char
类型的宽度和符号性以及字节序。只要字符编码仅使用 uint8_t
范围内的值,它就不会发生冲突。
关于c - 如何在 C 中打开 4 个字符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8096441/