Skip to content

Instantly share code, notes, and snippets.

@junderw
Created July 8, 2020 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junderw/768c100128fa32dfd67ac2b652da763d to your computer and use it in GitHub Desktop.
Save junderw/768c100128fa32dfd67ac2b652da763d to your computer and use it in GitHub Desktop.
Functions to perform bitwise operations on unsigned ints up to 53 bit (highest JS precision) without bigint libraries.
var POW31 = 0x80000000
var MSK31 = 0x7FFFFFFF
function checkBitSize(bs) {
if (bs > 53 || bs < 1 || Math.floor(bs) !== bs) {
throw new Error('Invalid Bit Size')
}
}
function splitBits(val, size) {
if (val >= Math.pow(2, size) || val < 0 || Math.floor(val) !== val) {
throw new Error('Invalid value')
}
var upperSize = size > 31 ? size - 31 : 0
var upperMask = Math.pow(2, upperSize) - 1
return [
Math.floor(val / POW31) & upperMask,
val & MSK31,
]
}
function xor(a, b, bitsize) {
bitsize = bitsize || 53
checkBitSize(bitsize)
var aS = splitBits(a, bitsize)
var bS = splitBits(b, bitsize)
aS[0] ^= bS[0]
aS[1] ^= bS[1]
return aS[0] * POW31 + aS[1]
}
function and(a, b, bitsize) {
bitsize = bitsize || 53
checkBitSize(bitsize)
var aS = splitBits(a, bitsize)
var bS = splitBits(b, bitsize)
aS[0] &= bS[0]
aS[1] &= bS[1]
return aS[0] * POW31 + aS[1]
}
function or(a, b, bitsize) {
bitsize = bitsize || 53
checkBitSize(bitsize)
var aS = splitBits(a, bitsize)
var bS = splitBits(b, bitsize)
aS[0] |= bS[0]
aS[1] |= bS[1]
return aS[0] * POW31 + aS[1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment