-4

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.

Arnold
  • 185
  • 1
  • 2
  • 8

1 Answers1

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