c - 如何在 C 中打开 4 个字符的字符串?

标签 c string macros switch-statement

我需要根据 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_tuint32_t 的存在,并且与 char 类型的宽度和符号性以及字节序。只要字符编码仅使用 uint8_t 范围内的值,它就不会发生冲突。

关于c - 如何在 C 中打开 4 个字符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8096441/

相关文章:

c - 如何从调用者分配的内存空间中捕获由被调用者组织的字符串数组?

java - 在这里拆分字符串的好方法是什么?

c - 为什么 "do ... while (0)"不能用简单的大括号代替?

javascript - Sweet.js - 宏主体中的括号

c - 使用结构获取学生的姓名和分数

c - 从一个线程停止 main

c - 从数字字符串中获取位

java - Java中如何打印String的中间三个字符?

macros - 在 Lisp 中是否可以取消定义宏和函数?

c++ - 在 C 或 C++ 中不使用 header 进行编码有哪些客观原因?