Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- needed because the toBinary function returns the bit in a reversed order
- local function reverseTable(t)
- local r={};
- for i=#t,1,-1 do
- r[#r+1]=t[i];
- end;
- return r;
- end;
- -- getBits function get the bits of an integer
- local function getBits(int)
- local bits={};
- while(int>0)do
- bit=int%2;
- bits[#bits+1]=bit;
- int=(int-bit)/2;
- end;
- return bits; --the bits are in reversed order ok
- end;
- -- parse the integers to bits that can get processed
- local function parseIntegers(a,b)
- local ba=reverseTable(getBits(a));
- local bb=reverseTable(getBits(b));
- while(#ba<#bb)do --{{
- ba={0,unpack(ba)};
- end; --because the bits need to be of equivalent length
- while(#ba>#bb)do
- bb={0,unpack(bb)};
- end; --}}
- return ba,bb;
- end;
- -- bitwise and
- local function band(a,b)
- local resBits={};
- local ba,bb=parseIntegers(a,b);
- for i=1,#ba do
- resBits[#resBits+1]=ba[i]*bb[i];
- end;
- local res=tonumber(table.concat(resBits),2);
- print(res);
- end;
- -- bitwise or
- local function bor(a,b)
- local resBits={};
- local ba,bb=parseIntegers(a,b);
- for i=1,#ba do
- if((ba[i]==1)or(bb[i]==1))then
- resBits[#resBits+1]=1;
- else
- resBits[#resBits+1]=0;
- end;
- end;
- local res=tonumber(table.concat(resBits),2);
- print(res);
- end;
- -- bitwise xor
- local function bxor(a,b)
- local resBits={};
- local ba,bb=parseIntegers(a,b);
- for i=1,#ba do
- if(ba[i]==bb[i])then
- resBits[#resBits+1]=0;
- else
- resBits[#resBits+1]=1;
- end;
- end;
- local res=tonumber(table.concat(resBits),2);
- print(res);
- end;
- --bitwise not
- local function bnot(a)
- a=-a-1;
- print(a);
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement