简体   繁体   中英

How to cast for bitwise shift

I am trying to combine bits read in different 16-bit register into a single 32-bit variable with bit shifting (this is to get an ID stored split in different register in an interesting way on a sensor).

But there should have something about casting and bit shifting I am missing. Especially I cannot comprehend why in the example below sum and id0_d + id1_d lead to different results. I would prefer a solution like the way sum is computed without having to declare intermediate variables.

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint16_t id0 = 0x4E00;
    uint16_t id1 = 0xABCD;
    uint32_t sum = ((uint32_t)id0)>>7 + ((uint32_t)id1)<<9;
    uint32_t id0_d = ((uint32_t)id0)>>7;
    uint32_t id1_d = ((uint32_t)id1)<<9;
    
    printf("id0: %04X\n", id0);
    printf("id1: %04X\n", id1);
    printf("sum: %08lx\n", sum);
    printf("id0_d: %08lx\n", id0_d);
    printf("id1_d: %08lx\n", id1_d);
    printf("id0+1_d: %08lx\n", id0_d + id1_d);
    return 0;
}

Which outputs the following:

id0: 4E00
id1: ABCD
sum: 00000000
     ^no the expected result
id0_d: 0000009c
id1_d: 01579a00
id0+1_d: 01579a9c
         ^expected result for "sum"

Edit the following:

uint32_t sum = ((uint32_t)id0)>>7 + ((uint32_t)id1)<<9;
uint32_t id0_d = ((uint32_t)id0)>>7;
uint32_t id1_d = ((uint32_t)id1)<<9;

to: ensure that the operations are performed in the right order:

uint32_t sum = ((uint32_t)id0>>7) | ((uint32_t)id1<<9);
uint32_t id0_d = (uint32_t)id0>>7;
uint32_t id1_d = (uint32_t)id1<<9;

Using the arithmetic operator + in this example will produce the expected results, but with bitwise operations, the bitwise | is more commonly used

printf("id0+1_d: %08lx\n", id0_d + id1_d);

to

printf("id0+1_d: %08lx\n", id0_d | id1_d);

This will result in the expected output:

在此处输入图像描述

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