简体   繁体   中英

Convert and mask bits of little endian to big endian

I am working on a Qt/C++ application. I want to show state of 3 hall sensors so I read it from micro-controller this way:

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.

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. 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.

Here is my code on 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.

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

If you can I suggest you to use Boost C++ libraries: in this link you can find all you need.

If you're using GCC you can use the int32_t __builtin_bswap32 (int32_t x)

Alternative you can write you own function... it's quite easy, at this post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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