RosettaCodeData/Task/Bitwise-IO/Lingo/bitwise-io-1.lingo

64 lines
1.9 KiB
Plaintext

-- parent script "BitArray"
property ancestor
property bitSize
property _pow2
----------------------------------------
-- @constructor
-- @param {integer} [bSize=0]
----------------------------------------
on new (me, bSize)
if voidP(bitSize) then bitSize=0
me.bitSize = bSize
byteSize = bitSize/8 + (bitSize mod 8>0)
me._pow2 = [128,64,32,16,8,4,2,1] -- pow2 lookup list
me.ancestor = ByteArray(byteSize)
return me
end
----------------------------------------
-- Sets bit at position <bitPos> to <bitValue>.
-- @param {integer} bitPos - starts at 1, as ByteArray's native byte access functions
-- @param {boolean} bitValue
----------------------------------------
on setBit (me, bitPos, bitValue)
bytePos = (bitPos-1)/8 + 1
bitPos = (bitPos-1) mod 8 + 1
if bitValue then
me[bytePos] = bitOr(me[bytePos], me._pow2[bitPos])
else
me[bytePos] = bitAnd(me[bytePos], bitNot(me._pow2[bitPos]))
end if
end
----------------------------------------
-- Gets bit value at position <bitPos>.
-- @param {integer} bitPos - starts at 1, as ByteArray's native byte access functions
-- @return {boolean} bitValue
----------------------------------------
on getBit (me, bitPos)
bytePos = (bitPos-1)/8 + 1
bitPos = (bitPos-1) mod 8 + 1
return bitAnd(me[bytePos], me._pow2[bitPos])<>0
end
----------------------------------------
-- Returns all bits as string. To be in accordance with ByteArray's native toHexString(),
-- returned string is separated with SPACE (e.g. "0 1 1 0...")
-- @param {integer} [bitSizeOnly=FALSE] - if TRUE, only <bitSize> bits without byte-padding
-- @return {string}
----------------------------------------
on toBinString (me, bitSizeOnly)
res = ""
repeat with i = 1 to me.length
byte = me[i]
repeat with j = 1 to 8
put (bitAnd(byte, me._pow2[j])<>0)&" " after res
if bitSizeOnly and (i-1)*8+j=me.bitSize then exit repeat
end repeat
end repeat
delete the last char of res
return res
end