简体   繁体   English

将Little Endian的位转换并屏蔽为Big Endian

[英]Convert and mask bits of little endian to big endian

I am working on a Qt/C++ application. 我正在研究Qt / C ++应用程序。 I want to show state of 3 hall sensors so I read it from micro-controller this way: 我想显示3个霍尔传感器的状态,因此我以这种方式从微控制器读取了它:

uint8_t state = getState(whichMotor);
int numChars = sprintf(sBuff, "%d", state);
HAL_UART_Transmit_DMA(&huart3, sBuff, numChars);

State can be any 1, 5, 4, 6, 2 or 3. 状态可以是1、5、4、6、2或3。

Then in my Qt application I have 3 labels and want to show if corresponding bit is set in the number I receive from UART. 然后在我的Qt应用程序中,我有3个标签,想要显示从UART接收到的号码中是否设置了相应的位。 I am sure I get the correct number, when I show it as integer its fine. 当我将其显示为整数时,我确定我得到了正确的数字。 But to break it down into 3 bits into three labels I fail as it just shows 1 1 1 or 0 0 0. 但是将其分为3个标签分成3个标签,我失败了,因为它只显示1 1 1或0 0 0。

Here is my code on PC: 这是我在PC上的代码:

const void MotorWidget::setHallState(const QString& s)
{
 int hallState = s.toInt();
 ui->lbValueHallC->setText(hallState & 0b100 > 0 ? "1" : "0");
 ui->lbValueHallB->setText(hallState & 0b010 > 0 ? "1" : "0");
 ui->lbValueHallA->setText(hallState & 0b001 > 0 ? "1" : "0");
}

For example, if I receive hallState as 5, label C should show "1", label B should show "0" and label A should show "1"...but as I said I only get 111 or 000 regardless of what I receive. 例如,如果我收到hallState为5,则标签C应该显示为“ 1”,标签B应该显示为“ 0”,标签A应该显示为“ 1” ...但是正如我说的,无论我做什么,我只会得到111或000。接收。

I suspect this might be big-endian little-endian thing...but I have no idea how to fix it 我怀疑这可能是大端小端的事情...但是我不知道如何解决它

Maybe add some parentheses: 也许加上一些括号:

const void MotorWidget::setHallState(const QString& s)
{
 int hallState = s.toInt();
 ui->lbValueHallC->setText((hallState & 0b100) > 0 ? "1" : "0");
 ui->lbValueHallB->setText((hallState & 0b010) > 0 ? "1" : "0");
 ui->lbValueHallA->setText((hallState & 0b001) > 0 ? "1" : "0");
}

Also have a look here: http://en.cppreference.com/w/cpp/language/operator_precedence 也可以在这里查看: http : //en.cppreference.com/w/cpp/language/operator_precedence

If you can I suggest you to use Boost C++ libraries: in this link you can find all you need. 如果可以的话,我建议您使用Boost C++库:在此链接中,您可以找到所需的全部。

If you're using GCC you can use the int32_t __builtin_bswap32 (int32_t x) 如果您使用的是GCC ,则可以使用int32_t __builtin_bswap32 (int32_t x)

Alternative you can write you own function... it's quite easy, at this post 替代你可以写你自己的功能... ...这是很容易的,在这个帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM