【发布时间】:2020-08-05 09:20:28
【问题描述】:
我想通过按位运算将 3 个无符号整数值存储到 uint16_t 变量中,并使用按位运算将它们读回。以下是我的程序:
代码:
#include <iostream>
uint16_t Write(unsigned int iVal1, unsigned int iVal2, unsigned int iVal3) {
// iVal1 should go into the first 8 bits [iVal1 value ranges from 0 to 173]
// iVal2 should go into the 6 bits after that [iVal2 value ranges from 0 to 63]
// iVal3 should go into the 2 bits after that [iVal3 value ranges from 0 to 3]
// Is the below way of writing the bits correct?
return (static_cast<uint16_t>(iVal1)<<8) + (static_cast<uint16_t>(iVal2)<<6) + (static_cast<uint16_t>(iVal3)<<2);
}
unsigned int ReadVal1(const uint16_t theNumber) {
// ival1 is the first 8 bits
uint16_t check1 = 255;
return (theNumber>>8)&check1;
}
unsigned int ReadVal2(const uint16_t theNumber) {
// ival2 is the 6 bits after that
uint16_t check2 = 63;
return (theNumber>>3)&check2;
}
unsigned int ReadVal3(const uint16_t theNumber) {
// ival3 is the last 2 bits
uint16_t check3 = 3;
return (theNumber>>1)&check3;
}
int main() {
std::cout << "Main started" << std::endl;
unsigned int iVal1 = 191;
unsigned int iVal2 = 28;
unsigned int iVal3 = 3;
const uint16_t theNumber = Write(iVal1, iVal2, iVal3);
std::cout << "The first 8 bits contain the number: " << ReadVal1(theNumber) << std::endl;
std::cout << "Then after 6 bits contain the number: " << ReadVal2(theNumber) << std::endl;
std::cout << "Then after 2 bits contain the number: " << ReadVal3(theNumber) << std::endl;
}
在上面的程序中,下面是需要编码的3个无符号整数的范围。
`iVal1` ranges from `0 to 173`. So its well within 8 bits.
`iVal2` ranges from `0 to 63`. So its well within 6 bits.
`iVal3` ranges from `0 to 3`. So its well within 2 bits.
问题:
我认为我在函数Write 中编写值的方式是错误的。正确的方法是什么?
首先,我正在寻找一个很好的解释,说明使用按位运算的编码是如何工作的,尤其是在我上面的程序目标的上下文中。
我相信我在函数ReadVal1、ReadVal2 和ReadVal3 中读取值的方式是正确的。我已经想出了如何读回看起来很容易的值的技巧。但是,我不能很好地理解如何使用按位运算正确编码值的逻辑。
C++ 编译器:
我正在使用 C++11 编译器
【问题讨论】:
-
我更新了问题以显示需要编码的 3 个无符号整数的范围
-
你的
write错了,你的read也错了。您需要移位的位数不是您要读取和写入的整数的大小,而是所有剩余整数的组合大小(因为您正在移位以便为 那些)。最后一个整数根本不应该移动。您在read上右移的位数应该与您在write上左移的位数完全相同。>>3和>>1的来源是个谜。 -
啊,我的阅读也错了!这真是很好的信息。那么我想要移动的位数是所有剩余整数的组合大小?你能解释一下吗?感谢一百万查看
-
嗯,我认为这个解释已经足够好了。尝试用 8、2 和 0 替换移位值。我们将 second 整数左移 2 位,因为我们需要这 2 位来适应 third 整数。读取时,我们向后移动相同的 2 位。
-
谢谢!我根据您的解释弄清楚了该程序。所以第二个整数通常会占用剩余的 8 位。但是我们将它移动了 2 位,以便为最后一个腾出空间。如果我们想为 3 位腾出空间,那么我们将在写入期间左移 3 位。如果它在剩余位内,则默认情况下最后一个仅占用剩余位。我是否理解这个正确的@n.'pronouns'm。 ?
标签: c++11 bit-manipulation bitwise-operators bit-shift