我需要根据4个字符的字符串进行切换。我把字符串放在一个联合中,所以我至少可以把它称为32位整数。
union
{
int32u integer;
char string[4];
}software_version;
但现在我不知道在案例陈述中写什么。我需要某种宏来将4个字符的字符串文字转换为整数。 E.G。
#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()宏。或者有更好的方法来处理交换机吗?
答案 0 :(得分:7)
便携式示例代码:
#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
范围内的值,就没有冲突。
答案 1 :(得分:2)
你打开像这样的四个字符代码
switch (fourcc) {
case 'FROB':
}
注意区别:"XXXX"
是一个字符串,'XXXX'
是一个字符/整数文字。
但是,我建议您使用单独的版本号,例如:
struct Version {
int major, minor, patch;
};
bool smaller (Version lhs, Version rhs) {
if (lhs.major < rhs.major) return true;
if (lhs.major > rhs.major) return false;
if (lhs.minor < rhs.minor) return true;
if (lhs.minor > rhs.minor) return false;
if (lhs.patch < rhs.patch) return true;
if (lhs.patch > rhs.patch) return false; // redundant, for readabiltiy
return false; // equal
}
答案 2 :(得分:0)
更新:
#define VERSION_2_3_7 '0237'
答案 3 :(得分:-2)
int versionstring_to_int(char * str)
{
char temp [ 1+ sizeof software_version.string ]; /* typically 1+4 */
if (!str || ! *str) return -1;
memcpy (temp, str, sizeof temp -1);
temp [sizeof temp -1] = 0;
return atoi (temp );
}
编辑:
#define STRING_TO_INTEGER(s) versionstring_to_int(s)
#define VERSION_2_3_7 237
#define VERSION_2_4_1 241
switch ( STRING_TO_INTEGER( array[i].software_version.string) )
{
case VERSION_2_3_7:
break;
case VERSION_2_4_1:
break;
}