I wish to store either 0 or 1 in each bit of an allocated memory. For example I have char *block_of_memory = (char *)malloc(125000 * sizeof(char))
, here I have 125000 * 8 bits = 1000,000 bits of memory. How can I access each bit and give it a value as 0 or 1. Say , I want to make the 20th bit to 1 and 21st bit as 0.
Asked
Active
Viewed 5,071 times
-4

Arnold
- 185
- 1
- 2
- 8
-
`(block_of_memory[bit/8] >> (bit % 8)) & 1` – Colonel Thirty Two May 02 '15 at 21:27
-
First you find out which byte you need to change, then which bit in that byte. The first is done by dividing the bit number by 8, the second by looking at the remainder of that operation. – Peter - Reinstate Monica May 02 '15 at 21:27
-
1http://stackoverflow.com/q/47981/62576 – Ken White May 02 '15 at 21:27
-
@KenWhite And there, specifically answer http://stackoverflow.com/a/3234773/3150802. – Peter - Reinstate Monica May 02 '15 at 21:31
-
Is this right way to set the 20th bit to 1? (block_of_memory[20/8] >> (20 % 8)) & 1 – Arnold May 02 '15 at 21:31
1 Answers
2
You need to calculate a byte offset and a bitmask within that byte.
- Set the bit: bitwise OR with mask
- Clear the bit: bitwise AND with complement of mask
- Read the bit: return bitwise AND of byte and mask
The code:
void set_bit(char *buf, int bit, int val)
{
int byte = bit / 8;
char mask = 1 << (bit % 8);
if (val)
buf[byte] |= mask;
else
buf[byte] &= ~mask;
}
int get_bit(char *buf, int bit)
{
int byte = bit / 8;
char mask = 1 << (bit % 8);
return buf[byte] & mask ? 1 : 0;
}
Example: Set bit 17 to 1. Byte offset is 17/8 = 2
. Bit offset is 17%8 = 1
. The bitmask is generated by left-shifting 1 by the bit offset: results in 00000010
binary. Bitwise OR byte[2]
with it: all bits remain the same, except where the mask bit is 1.

SzG
- 12,333
- 4
- 28
- 41
-
Thanks! Can you explain the mask please? Why and How are we using it here? – Arnold May 03 '15 at 19:35