From da54010cf25b7168e561ff8142b4a0f80c5d53ec Mon Sep 17 00:00:00 2001 From: flip111 Date: Sun, 8 Oct 2023 23:54:05 +0200 Subject: [PATCH] Add single bit functions --- src/Data/Int/Bits.js | 33 ++++++++++++++++++++++++++++++++ src/Data/Int/Bits.purs | 43 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/src/Data/Int/Bits.js b/src/Data/Int/Bits.js index 49bbaff..7677ddc 100644 --- a/src/Data/Int/Bits.js +++ b/src/Data/Int/Bits.js @@ -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; + } +}; diff --git a/src/Data/Int/Bits.purs b/src/Data/Int/Bits.purs index d1b4715..c4412c3 100644 --- a/src/Data/Int/Bits.purs +++ b/src/Data/Int/Bits.purs @@ -7,6 +7,12 @@ module Data.Int.Bits , shr , zshr , complement + , zeroBits + , bit + , setBit + , clearBit + , complementBit + , testBit ) where -- | Bitwise AND. @@ -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