Forum

> > CS2D > Scripts > Bitwise operations
Forums overviewCS2D overview Scripts overviewLog in to reply

English Bitwise operations

2 replies
To the start Previous 1 Next To the start

old Bitwise operations

archmage
User Off Offline

Quote
I wrote this so I could do bit operations in Lua. I thought someone else might need it so I am posting it.

Function list
Quote
tobits (n)
     n - number to convert to binary/bits

     returns a table of bits

BitOp (n, n2, bits, c)
     n - first number
     n2 second number
     bits - max bits (default 8 (1 byte/octet))
     c - bitop function to use (default and)

     performs c on each bit in n and n2

NOT (n)
     n - number

     returns n except with the bits negated

LSHIFT (n, s)
     n - number
     s - number of shifts (default 1)

     shifts each bit in n to the left s times

RSHIFT (n, s)
     n - number
     s - number of shifts (default 1)

     shifts each bit in n to the right s times


BitOp functions
Use these as the c parameter of BitOp
Quote
bitop_or perform or on the bits
bitop_xor perform exclusive or on the bits
bitop_and perform and on the bits


Source
More >
edited 1×, last 26.04.11 02:07:47 am

old Re: Bitwise operations

Flacko
User Off Offline

Quote
Darkbyte, I think it's unnecessary to have a "LSHIFT" and "RSHIFT" function. Just make a "SHIFT" function and make it so that negative values move the bits to the left and positive values move it to the right.

Something like this:
1
2
3
4
5
6
7
function bit:shift(shift)
	local start, finish, increase = 1,#self,1
	if shift < 0 then start,finish,increase = #self,1,-1 end
	for i=start,finish,increase do
		if i+shift>#self or i+shift<1 then self[i]=false else self[i]=self[i+shift] end
	end
end
But I'm not sure it will work with your code...

EDIT: I also think you should use tables with boolean values instead of numbers. If you do so, you can write functions in a much nicier-looking way:
1
2
3
4
5
6
--Binary NOT example
function bit:bnot()
	for i=1, #self do
		self[i] = not self[i]
	end
end
edited 1×, last 26.04.11 10:57:11 am
To the start Previous 1 Next To the start
Log in to reply Scripts overviewCS2D overviewForums overview