gpt4 book ai didi

c - 按位组以字节为单位设置各个位

转载 作者:行者123 更新时间:2023-11-30 17:53:11 26 4
gpt4 key购买 nike

例如:

We have a byte A: XXXX XXXX
We have a byte B: 0000 0110

现在,例如,我们需要字节 B 中特定位置的 4 位,并且我们希望将字节 A 放入特定位置,这样我们就得到了结果:

We have a byte A: 0110 XXXX

我仍在寻找神奇的功能,但没有成功。

发现类似并对其进行了修改,但仍然没有结局:

unsigned int i, j; // positions of bit sequences to swap
unsigned int n; // number of consecutive bits in each sequence
unsigned int b; // bits to swap reside in b
unsigned int r; // bit-swapped result goes here

unsigned int x = ((b >> i) ^ (b >> j)) & ((1U << n) - 1); // XOR temporary
r = b ^ ((x << i) | (x << j));
As an example of swapping ranges of bits suppose we have have b = 00101111 (expressed in binary) and we want to swap the n = 3 consecutive bits starting at i = 1 (the second bit from the right) with the 3 consecutive bits starting at j = 5; the result would be r = 11100011 (binary).
This method of swapping is similar to the general purpose XOR swap trick, but intended for operating on individual bits. The variable x stores the result of XORing the pairs of bit values we want to swap, and then the bits are set to the result of themselves XORed with x. Of course, the result is undefined if the sequences overlap.

最佳答案

很难准确理解您的要求,如果我错了,请纠正我:

您想要获取字节 (B) 的最后 4 位并将它们添加到字节 A 的第一个位吗?您使用了术语“放入内部”,但不清楚您的确切含义(如果不是添加,您的意思是替换吗?)。

所以假设加法是你想要的,你可以这样做:

A = A | (B <<4)

这将向左移动 4 位(从而以 01100000 结束),然后将其“添加”到 A(使用或)。

关于c - 按位组以字节为单位设置各个位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15764813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com