c - 将 4 字节值中的特定位提取到 C 中的新变量中

标签 c bit-manipulation

我对位操作非常陌生。

假设我有一个 32 位值 myInput4ByteValue

从这个 32 位值中,我需要提取位 25 ..2

这里最好的方法是什么? 我的想法是将它们分成 3 个字节并复制其中的值:

struct myOutput3ByteValue.
{
    uint8 FirstPart //  Bits 9..2  Least Significant 8 Bits from myInput4ByteValue.
    uint8 SecondPart // Bits 17 ..10
    uint8 ThirdPart  // Bits 25 ..18
}

我开始于:

myOutput3ByteValue.FirstPart = (myInput4ByteValue & 0x3FC0) // Here I will the bits 9..2
myOutput3ByteValue.SecondPart = ...?                        //How to fill the rest?

我真的不确定我是否开始正确。 建议会很有帮助。

我将它们分成 3 个字节的原因是因为我在末尾将有一个自己的 3 字节类型,我必须使用它来处理它。

最佳答案

你那里的东西不会完全起作用。 0x3FC0是一个 16 位 int,而你将它分配给一个 8 位 int,所以它会被截断。您需要位移<<>> 。 所以位 9..2 是:

FirstPart = (value >> 1); // No need to mask as bits 9+ will be truncated
SecondPart = (value >> 9); // Second set of 8 bits

关于c - 将 4 字节值中的特定位提取到 C 中的新变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58560359/

相关文章:

c++ - 输出 float 进行调试

用 C 比较两个数组

c++ - 需要一些帮助 - 左移按位运算符

rust - 翻转 boolean 值的最快方法

c - 使用指针进行位操作

c - 带有按位运算符的 Termios 语法配置

java - 如何检查十六进制字符串中是否设置了位?

无法从 LPT1 获取端口句柄

c - 如何删除从 C 中的 fgets 输入的额外字符?

c - 错误 - 00352D10 处的堆 block 在 00352D1C 处修改,超过了请求的大小 4