Advertisement
Basswobble

Lua 5.1 Bitwise Operators

Jan 12th, 2014
737
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.63 KB | None | 0 0
  1. -- needed because the toBinary function returns the bit in a reversed order
  2.  
  3. local function reverseTable(t)
  4.     local r={};
  5.     for i=#t,1,-1 do
  6.         r[#r+1]=t[i];
  7.     end;
  8.     return r;
  9. end;
  10.  
  11. -- getBits function get the bits of an integer
  12.  
  13. local function getBits(int)
  14.     local bits={};
  15.     while(int>0)do
  16.         bit=int%2;
  17.             bits[#bits+1]=bit;
  18.             int=(int-bit)/2;
  19.     end;
  20.     return bits; --the bits are in reversed order ok
  21. end;
  22.  
  23.  
  24. -- parse the integers to bits that can get processed
  25.  
  26. local function parseIntegers(a,b)
  27.     local ba=reverseTable(getBits(a));
  28.     local bb=reverseTable(getBits(b));
  29.     while(#ba<#bb)do        --{{
  30.         ba={0,unpack(ba)};  
  31.     end;                        --because the bits need to be of equivalent length
  32.     while(#ba>#bb)do       
  33.         bb={0,unpack(bb)}; 
  34.     end;                    --}}
  35.     return ba,bb;  
  36. end;
  37.  
  38. -- bitwise and
  39.  
  40. local function band(a,b)
  41.     local resBits={};
  42.     local ba,bb=parseIntegers(a,b);
  43.     for i=1,#ba do
  44.         resBits[#resBits+1]=ba[i]*bb[i];
  45.     end;
  46.     local res=tonumber(table.concat(resBits),2);
  47.     print(res);
  48. end;
  49.  
  50. -- bitwise or
  51.  
  52. local function bor(a,b)
  53.     local resBits={};
  54.     local ba,bb=parseIntegers(a,b);
  55.     for i=1,#ba do
  56.         if((ba[i]==1)or(bb[i]==1))then
  57.             resBits[#resBits+1]=1;
  58.         else
  59.             resBits[#resBits+1]=0;
  60.         end;
  61.     end;
  62.     local res=tonumber(table.concat(resBits),2);
  63.     print(res);
  64. end;
  65.  
  66. -- bitwise xor
  67.  
  68. local function bxor(a,b)
  69.     local resBits={};
  70.     local ba,bb=parseIntegers(a,b);
  71.     for i=1,#ba do
  72.         if(ba[i]==bb[i])then
  73.             resBits[#resBits+1]=0;
  74.         else
  75.             resBits[#resBits+1]=1;
  76.         end;
  77.     end;
  78.     local res=tonumber(table.concat(resBits),2);
  79.     print(res);
  80. end;
  81.  
  82. --bitwise not
  83.  
  84. local function bnot(a)
  85.     a=-a-1;
  86.     print(a);
  87. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement