Forum

> > CS2D > Scripts > Bitwise operations
ForenübersichtCS2D-Übersicht Scripts-ÜbersichtEinloggen, um zu antworten

Englisch Bitwise operations

2 Antworten
Zum Anfang Vorherige 1 Nächste Zum Anfang

alt Bitwise operations

archmage
User Off Offline

Zitieren
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
Zitat
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
Zitat
bitop_or perform or on the bits
bitop_xor perform exclusive or on the bits
bitop_and perform and on the bits


Source
Mehr >
1× editiert, zuletzt 26.04.11 02:07:47

alt Re: Bitwise operations

Flacko
User Off Offline

Zitieren
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
1× editiert, zuletzt 26.04.11 10:57:11
Zum Anfang Vorherige 1 Nächste Zum Anfang
Einloggen, um zu antworten Scripts-ÜbersichtCS2D-ÜbersichtForenübersicht