Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/Data/Int/Bits.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,36 @@ export const complement = function (n) {
/* jshint bitwise: false */
return ~n;
};

export const zeroBits = 0;

export const bit = function (n) {
return function (pos) {
return (1 << pos);
}
};

export const setBit = function (n) {
return function (pos) {
return n | (1 << pos);
}
};

export const clearBit = function (n) {
return function (pos) {
const mask = ~(1 << pos);
return n & mask;
}
};

export const complementBit = function (n) {
return function (pos) {
return n ^ (1 << pos);
}
};

export const testBit = function (n) {
return function (pos) {
return (n & (1 << pos)) === 0 ? 0 : 1;
}
};
43 changes: 43 additions & 0 deletions src/Data/Int/Bits.purs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ module Data.Int.Bits
, shr
, zshr
, complement
, zeroBits
, bit
, setBit
, clearBit
, complementBit
, testBit
) where

-- | Bitwise AND.
Expand Down Expand Up @@ -35,3 +41,40 @@ foreign import zshr :: Int -> Int -> Int

-- | Bitwise NOT.
foreign import complement :: Int -> Int

-- | zeroBits is the value with all bits unset.
zeroBits :: Int
zeroBits = 0

-- | bit i is a value with the i'th bit set and all other bits clear.
foreign import bit :: Int -> Int

-- | Set a bit
-- |
-- | ```purescript
-- | setBit 0 1 == 2
-- | ```
foreign import setBit :: Int -> Int -> Int

-- | Clear a bit
-- |
-- | ```purescript
-- | clearBit 7 1 == 5
-- | ```
foreign import clearBit :: Int -> Int -> Int

-- | XOR a bit
-- |
-- | ```purescript
-- | complementBit 7 1 == 5
-- | complementBit 0 1 == 2
-- | ```
foreign import complementBit :: Int -> Int -> Int

-- | Test a bit
-- |
-- | ```purescript
-- | testBit 0 1 == false
-- | testBit 7 1 == true
-- | ```
foreign import testBit :: Int -> Int -> Boolean