Search code examples
mathluabit

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. 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;

Solution

  • It's reading WWXXYYZZ
    A byte, holds values from 0-255 ( 0x00 to 0xFF ) so W holds those.

    To count any higher that, you need to multiply by 256.
    (X * 256)

    any higher that, you need to multiply again by 256.
    (Y * 256 *256) is the same as (Y * 65536)

    And finally, multiply again by 256.
    (Z * 256 *256 *256) is the same as (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. Let's say it's RGBA. ok, now you have a dim red pixel, but where's your green, blue and alpha channels?

    That's why they are multiplied, so that the entire construct can be serialized.
    3 + (4 *256) + (5 *256 *256) + (6 *256 *256 *256) = ...
    I'm not gonna math it, you get the idea.