Search code examples
javascriptjavatypescriptbit

Java/JS/TS Given row and column get bit value in truthtable


Is their a short formula for calculating the bit value for a given row and column? Example: getTTBit(row = 3, col = 2) = 1

4 2 1
0 0 0
0 0 1
0 1 0
0 1 1 <-- row 3, col 2 -> 1
1 0 0
1 0 1
1 1 0
1 1 1

It should be as quick as possible. I dont want to convert the row number into a bitarray and get the col'th element because I work with large numbers (rows). My bad current solution looks like this (TS):

export function getTTBit(numCols: number, row: number, col: number): bit {
    return getNumberAsBitArray(row, numCols)[col];
}

export function getNumberAsBitArray(n: number, length: number): bit[] {
    return [...Array(length)].map((_, i) => n >> i & 1).reverse() as bit[];
}

Solution

  • basically, you're asking how to check if the Nth bit is set in a number?

    This is the same in all three languages:

    isSet = (row & (1 << col)) != 0
    

    where col is counted from the right (lsb=0).