How can I store value in bit in C language
This question already has an answer here:
You need to calculate a byte offset and a bitmask within that byte.
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.
上一篇: 打开和关闭LED的功能
下一篇: 如何以C语言存储价值?