在 C 中将布尔字符串解释为数字的最快方法是什么? [英] What's the fastest way to interpret a bool string into a number in C?

查看:48
本文介绍了在 C 中将布尔字符串解释为数字的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用谷歌搜索,所有结果都是关于 C++ 和 C#,所以我问了一个 C 特定问题.

I googled it and all the results were about C++ and C# so I am asking a C specific question.

// Str to lower
if (!memcmp(Str, "true", 4) || !memcmp(Str, "1", 1) || ...) {
     return 1;
} else if (!memcmp(Str, "false", 5) || !memcmp(Str, "0", 1) || ...) {
     return 0;
}
return -1;

这是一种方法.但我不太确定这是最有效的方法.将布尔字符串(例如true")解释为等效值 1 的最有效方法是什么?

That's one way to do it. But I'm not quite sure that's the most efficient way to do it. What's the most efficient way to interpret a bool string (eg. "true") into the equivalent value 1?

推荐答案

也许是一个简单的散列和测试?

Perhaps a simple hash and test?

#define Ttrue  (((uint_least64_t)'t') << 32 | ((uint_least64_t)'r') << 24 | ((uint_least64_t)'u') << 16 | ((uint_least64_t)'e') << 8 | 0)
#define T1     (((uint_least64_t)'1') << 8 | 0)
#define Tfalse (((uint_least64_t)'f') << 40 | ((uint_least64_t)'a') << 32 | ((uint_least64_t)'l') << 24 | ((uint_least64_t)'s') << 16 | ((uint_least64_t)'e') << 8 | 0)
#define T0     (((uint_least64_t)'0') << 8 | 0)

int Bool_str_decode(const char *Str) {
  uint_least64_t sum = 0;
  do {
    sum <<= 8;
    sum |= *(unsigned char*) Str;
  } while (*Str++ && (sum & 0xFF0000000000) == 0);  // loop to \0 or 6 characters

  if (sum == T1 || sum == Ttrue) return 1;
  if (sum == T0 || sum == Tfalse) return 0;
  return -1;
}

这篇关于在 C 中将布尔字符串解释为数字的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆