将位插入uint16_t [英] Insert bit into uint16_t
问题描述
在使用 uint16_t
时,是否有任何有效的算法允许将 bit
位插入到 index
位置?我尝试逐位读取 index
之后的内容,将所有这些位存储到 char
数组中,更改 index
处的位,增加 index
,然后再次循环,从数组中插入位,但是有没有更好的方法?因此,我知道如何获取,设置,取消设置或切换特定位,但是我想可能有比逐位处理更好的算法.
Is there any efficient algorithm that allows to insert bit bit
to position index
when working with uint16_t
? I've tried reading bit-by-bit after index
, storing all such bits into array of char
, changing bit at index
, increasing index
, and then looping again, inserting bits from array, but could be there a better way? So I know how to get, set, unset or toggle specific bit, but I suppose there could be better algorithm than processing bit-by-bit.
uint16_t bit_insert(uint16_t word, int bit, int index);
bit_insert(0b0000111111111110, 1, 1); /* must return 0b0100011111111111 */
P.S.该解决方案必须使用与ANSI兼容的纯C语言.我知道 0b
前缀可能是 gcc
所特有的,但是我在这里使用它是为了使事情更加明显./p>
P.S. The solution must be in pure ANSI-compatible C. I know that 0b
prefix may be specific to gcc
, but I've used it here to make things more obvious.
推荐答案
使用按位运算符:
#define BIT_INSERT(word, bit, index) \
(((word) & (~(1U << (index)))) | ((bit) << (index)))
这篇关于将位插入uint16_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!