How can I store value in bit in C language

This question already has an answer here:

  • How do you set, clear, and toggle a single bit? 26 answers

  • 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.

    链接地址: http://www.djcxy.com/p/28808.html

    上一篇: 打开和关闭LED的功能

    下一篇: 如何以C语言存储价值?