"1 << 和有什么区别?x"和“pow(2, x)"? [英] What is the difference between "1 << x" and "pow(2, x)"?

查看:31
本文介绍了"1 << 和有什么区别?x"和“pow(2, x)"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在使用 Unity 时,我不得不使用按位运算符.现在,不要误会我的意思,我完全意识到按位运算符的用处,并且在某些情况下,它不能被替换而不必编写一堆丑陋的代码.问题更像是... a和b有什么区别,在这里:

So, while using Unity, there was a point where I had to use bitwise operators. Now, don't get me wrong, I'm fully aware of the usefulness of bitwise operators, and in several cases it cannot be replaced without having to make a bunch of ugly code. The question is more like... What's the difference between a and b, here:

double a = 1 << 3;
double b = Math.Pow(2, 3);

根据我对函数和二进制的理解,在这两种情况下,您最终都会在第四个位置得到 1,这等于 8...是什么阻止了任何人在按位运算符上使用 Math.pow?它真的会改变什么吗?

From my understanding of both functions and binary, in both cases, you end up with a 1 in the fourth position, and this equals 8... What prevents anyone from using Math.pow over a bitwise operator? Would it really change something?

推荐答案

一般来说,对于大多数语言:

In general terms, for most languages:

pow 函数的效率可能较低,因为它本质上是通用的,并且可以将任何数字提高到任何幂,因此无法针对特殊情况轻松优化.

The pow function is likely to be less efficient, as it essentially general purpose and can raise any number to any power, so cannot be optimized as easily for special cases.

位移将直接映射到处理器级别的操作.

The bit shifting will map directly to a processor level operation.

在某些语言中,编译器会看到操作具有恒定结果并使用该结果,但是如果稍微复杂一些,则可能会错过优化.

In some languages, the compiler would see that the operations have a constant result and use that, however if there is a little more complexity, then the optimization may be missed.

这篇关于&quot;1 &lt;&lt; 和有什么区别?x"和“pow(2, x)"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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