基于位选择的算法效率

发布于 2024-11-07 21:51:35 字数 396 浏览 4 评论 0原文

我想知道您在开发一种有效的算法来基于位进行 if/else 切换/情况方面的想法是什么。我有 8 位要使用,我需要将它们分为高阶位和低阶位,如下所示:

0000 1111

每半部分都包含一些打开位的信息库。例如,如果下半部分(在这个小端机器中为 1111)实际上是 0010,就会发生一些情况。此外,如果高端是1000,则会发生其他情况。

我想右移上半部分并进行 AND 比较(如 (x >> 4) & 8) 会很有效,但我不确定是什么对下半部分进行明智的处理,因为左移并与一些奇怪的数字进行比较似乎有点不明智。

再次非常感谢您的见解。

I was wondering what your ideas were in developing an efficient algorithm for doing if/else switch/cases based on bits. I have 8 bits to play with and I need to divide them into higher order and lower order bits, like so:

0000 1111

Each half contains some information base on which bits are turned on. For example, if the lower half (1111 in this little endian machine) is actually 0010, something happens. Furthermore, if the higher end is 1000, something else happens.

I guess it would be efficient to rightshift the upper half and make AND comparisons (like (x >> 4) & 8) but I'm not sure what's smart to do for the lower half, as it seems a bit unclever to left shift and compare to some weird number.

Your insights, again, greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜灵血窟げ 2024-11-14 21:51:35

首先,(x >> 4) &您的示例中的 8 不太正确。要将高半字节(前四位)与 n 进行比较,您需要 ((x >> 4) & 15) == n

要将低半字节与 n 进行比较,只需丢失右移即可:(x & 15) == n

First of all, the (x >> 4) & 8 in your example isn't quite right. To compare the higher nibble (the top four bits) to n, you need ((x >> 4) & 15) == n.

To compare the lower nibble to n, you simply lose the right shift: (x & 15) == n.

清晨说晚安 2024-11-14 21:51:35

要屏蔽低 4 位,您可以使用 bits & 0xf,如果您想检查这 4 位是否具有特定值(即 2 即 0010),您可以使用 (bits & 0xf ) == 2 作为下半部分, ( bits >> 4 ) == 2 表示上半部分。

当您只查看单个字节时,字节顺序没有任何区别。

To mask the lower 4 bits you can use bits & 0xf and if you want to check whether the 4 bits have a certain value (i.e. 2 which is 0010) you can use ( bits & 0xf ) == 2 for the lower half and ( bits >> 4 ) == 2 for the upper half.

Endianess makes no difference when you are looking at just a single byte.

腹黑女流氓 2024-11-14 21:51:35

我无法判断你是否想要像你所说的那样高效的东西,或者聪明的东西。如果你确实想要快速执行,没有什么比具有 256 个 case 的 switch 语句更快了。看一下编译器为 switch 生成的代码,您会发现它非常快。

如果你想要一些聪明的东西,那就是另一回事了。但是,无论它多么聪明,它永远不会比开关更快。

I can't tell whether you want something efficient, as you say, or something clever. If you really want fast execution, nothing is faster than a switch statement with 256 cases. Take a look at the code the compiler produces for switch and you'll see that it's very fast.

If you want something clever, that's a different deal. But, no matter how clever it is, it's never going to be faster than a switch.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文