将 int 按位转换为 UInt32 的最快方法?
我有一些低级图像/纹理操作,其中 32 位颜色存储为 UInt32 或 int,并且我需要在两者之间进行非常快速的按位转换。
例如
int color = -2451337;
//exception
UInt32 cu = (UInt32)color;
有什么想法吗?
谢谢和问候
i have some low level image/texture operations where 32-bit colors are stored as UInt32 or int and i need a really fast bitwise conversion between the two.
e.g.
int color = -2451337;
//exception
UInt32 cu = (UInt32)color;
any ideas?
thanks and regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这个问题和答案已经很老了,自最初提出以来,语言和标准库已经发展了很多,但我将提供一个适用于时代的更“现代”的答案。
这里的优点是没有装箱或强制转换,即使使用
unchecked
,这种情况仍然会发生。这仅仅提供了一种查看相同位的不同方式,类似于在 C 等语言中重新解释指针类型。与
Unsafe
的类名称相反,这并不被认为是不安全
代码,并且还可以很好地避免在与整数类型转换时对枚举进行装箱,但必须确保枚举与整数类型的位数相同。语言开发人员在此处对此技术进行了一些讨论。
This question and the answers are quite old, and the language and standard library have evolved quite a bit since it was originally asked, but I will supply a more "modern" answer that is applicable for the times.
The advantage here is that there is no boxing or cast, which is still occurring even when using
unchecked
. This merely provides a different way of looking at the same bits, analogous to reinterpreting a pointer type in a language like C.Contrary to the name of the class being
Unsafe
, this is not consideredunsafe
code, and also works well for avoiding boxing of enums when converting to/from integral types, though one must ensure that the enum is the same number of bits as the integer type.There is some discussion of this technique by the language developers here.
那些使用像 VB 这样的语言的人,在转换过程中没有一种非常方便的方法来禁用溢出检查,可以使用类似:
或
32 位的版本将非常相似。我不确定哪种方法会更快。这些转变有点愚蠢,但它们避免了“if”测试的需要。
Those using a language like VB, which don't have a really convenient way of disabling overflow checks during the conversion, could use something like:
or
Versions for 32 bits would be very similar. I'm not sure which approach would be faster. The shifts are a little silly, but they avoid the need for 'if' tests.