fanf: (Default)
[personal profile] fanf

So I needed some Lua functions to extract bit fields from an integral value, specifically struct stat.st_mode. Lua only has floating point numbers, and its standard library doesn't extend beyond ANSI C. So I wrote the following. (Note that a % b == a - floor(a/b)*b.)

   function mask(lobit, hibit, num)
      local toolo = num % 2^lobit
      return (num - toolo) % 2^hibit
   end

   function bit(bit, num)
      return num / 2^bit % 2 >= 1
   end

Date: 2008-05-07 09:19 (UTC)
From: [identity profile] bellinghman.livejournal.com
On a high theoretical level, all additions are subtractions, and all divisions are multiplications. In the latter case, finding the multiplicand is an exercise for the reader.

(Though it is an easy optimisation if it's a compile time known value. Or loop-invariant.)

June 2025

S M T W T F S
1234567
8 91011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated 2025-06-24 06:52
Powered by Dreamwidth Studios