简体   繁体   English

这个lua函数是怎么把位转换成32位的

[英]How does this lua function convert bits to 32 bit

I found this function and I'm trying to figure out how it converts each character which is 8 bits into 32 bits.我找到了这个函数,我想弄清楚它是如何将每个 8 位字符转换为 32 位的。 The code for the function is below.该函数的代码如下。

local function getBits32(streamString)
  local W, X, Y, Z  = string.byte(streamString, streamPosition, streamPositon + 3);
  
  streamPosition = streamPosition + 4;
  
  return (Z * 16777216) + (Y * 65536) + (X * 256) + W;
end;

It's reading WWXXYYZZ正在阅读 WWXXYYZZ
A byte, holds values from 0-255 ( 0x00 to 0xFF ) so W holds those.一个字节,保存从 0-255 (0x00 到 0xFF)的值,所以W保存这些值。

To count any higher that, you need to multiply by 256.要计算更高的值,您需要乘以 256。
(X * 256)

any higher that, you need to multiply again by 256.任何更高的值,您都需要再次乘以 256。
(Y * 256 *256) is the same as (Y * 65536) (Y * 256 *256)(Y * 65536)

And finally, multiply again by 256.最后,再次乘以 256。
(Z * 256 *256 *256) is the same as (Z * 16777216) (Z * 256 *256 *256)(Z * 16777216)

Add them all together, and none of those values overlap.将它们加在一起,这些值都不重叠。
Multiplying is just a programming trick to keep the values from collididing with one-another, so they can be streamed into the register in one sequential chunk.乘法只是一种防止值相互碰撞的编程技巧,因此它们可以在一个连续的块中流式传输到寄存器中。


If you took a values of 3, 4, 5, 6 and you just added them, without premultiplying, you'd get 18. That's no good because the computer has no idea where to put each byte.如果取 3、4、5、6 的值3, 4, 5, 6然后将它们相加,而不进行预乘,则会得到 18。这不好,因为计算机不知道将每个字节放在哪里。 Let's say it's RGBA.假设它是RGBA。 ok, now you have a dim red pixel, but where's your green, blue and alpha channels?好的,现在你有一个暗红色的像素,但是你的绿色、蓝色和 alpha 通道在哪里?

That's why they are multiplied, so that the entire construct can be serialized.这就是它们相乘的原因,以便可以序列化整个构造。
3 + (4 *256) + (5 *256 *256) + (6 *256 *256 *256) = ... 3 + (4 *256) + (5 *256 *256) + (6 *256 *256 *256) = ...
I'm not gonna math it, you get the idea.我不会计算它,你明白了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM