Jim Lahman
Jim Lahman

Reputation: 2767

Given a absolute bit number (ex. 24), how do I set the appropriate bit in an array of words?

I have an array of 16-bit words and I want to calculate the bit to set in the proper word when just given the bit number. For example, bit 24 sets the 8th bit in the 2nd word.

Upvotes: 0

Views: 96

Answers (1)

Marlon
Marlon

Reputation: 20312

Just use division to obtain the index in the array, and the remainder will be the bit number to set.

int N = 24;
int index = N / 16;
int bit = N % 16;

words[index] |= (1 << bit);

Upvotes: 8

Related Questions