Skip to content

Instantly share code, notes, and snippets.

@clauswitt
Created March 25, 2012 10:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clauswitt/2192677 to your computer and use it in GitHub Desktop.
Save clauswitt/2192677 to your computer and use it in GitHub Desktop.
A BitArray Implementation in CoffeeScript
class BitArray
width: 24
constructor: (size=24, default_value = 0) ->
@size = size
initialElements = Math.floor(size / @width) + 1
@field = []
for i in [0...initialElements]
@field[i] = 0
# Set a bit (1/0)
set: (position, value) ->
position -= 1
if value == 1
@field[Math.floor(position / @width)] |= 1 << (position % @width)
else if (@field[Math.floor(position / @width)]) & (1 << (position % @width)) != 0
@field[Math.floor(position / @width)] |= 0 << (position % @width)
return @
get: (position) ->
position -= 1
return if (@field[Math.floor(position / @width)] & 1 << (position % @width)) > 0 then 1 else 0
each: (callback) ->
i=0
while i < @size
callback @getValue(i), i
i++
return @
# Returns the field as a string like "0101010100111100," etc.
toString: ->
c = @
localField = @field.map (n) ->
val = n.toString(2)
while val.length < c.width
val = '0' + val;
val
str = localField.reverse().join('')
str.substr(str.length - c.size)
setFromString: (str) ->
vals = str.split('').reverse()
valCount = vals.length
for i in [0...valCount]
@set(i+1, parseInt(vals[i]))
return @
toArray: ->
return @field.slice()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment