C代码:左移是移位但是丢掉顶部位

时间:2015-05-20 14:43:23

标签: c shift

我正在做一个小型嵌入式项目,我通过SPI类型接口传输了40位。我将这些位从32位总线上拉下来,将高32位置为uint32_t变量,将低8位置入uint8_t变量。我试图将它们合并为一个uint64_t。但是,当我移动8时,它会降低前8位。这是我的代码。

uint64_t getError()
{
    uint32_t * disp_addr = (uint32_t*)(MYDISPLAY);

    uint64_t error_upper;
    uint8_t error_lower;
    uint64_t error= 0;

    error_lower = *(disp_addr+1);
    error_upper = *(disp_addr+0);
    error = ((uint64_t) error_upper) <<8 | error_lower;
    return error;
}

这段代码正在运行,除了它丢掉我的前8位这一事实。 任何想法或提示将不胜感激。感谢。

修改

uint64_t getError()
{
    uint32_t * disp_addr = (uint32_t*)(MYDISPLAY);

    uint64_t error_upper;
    uint8_t error_lower;
    uint64_t error= 0;

    error_lower = 0x34;
    error_upper = 0xABCDEF12;
    error = ((uint64_t) error_upper) <<8 | error_lower;
    printf("%010x", error);
    //return error;
}

结果: 00cdef1234

3 个答案:

答案 0 :(得分:4)

printf格式说明符不正确。

#include <stdio.h>

typedef unsigned __int64 uint64_t;
typedef unsigned char uint8_t;

int main(void) {
    uint64_t error_upper, error;
    uint8_t error_lower;

    error_lower = 0x34;
    error_upper = 0xABCEDF12;
    error = (error_upper << 8) | error_lower;
    printf("%x\n", error);
    printf("%llx\n", error);
    return 0;
}

节目输出:

cedf1234
abcedf1234

答案 1 :(得分:0)

为什么要说高位字节被切断? 如果我使用你的代码并打印结果就可以了:

uint32_t temp = 0x01020304;
uint32_t *disp_addr = &temp;
uint64_t error_upper;
uint8_t error_lower;
uint64_t error= 0;

error_lower = *(disp_addr+1);
error_upper = *(disp_addr+0);
error = (error_upper<<8) | error_lower;

printf("\n%08X%08X\n",  (uint32_t)(error>>32), error);

输出

0000000102030401

您是否使用%d打印输出值?

答案 2 :(得分:-1)

仔细看看

+(ACManager*)sharedInstance {
    static ACManager *sharedInstance;
    @synchronized(self) {
        if (!sharedInstance) {
            sharedInstance = [[self alloc]init];
        }
    }
    return sharedInstance;
}

-(void)login
{
    NSLog(@"login run");
}

@end

因为uint32_t *disp_addr = &temp; ... error_lower = *(disp_addr+0); 是uint32_t的ptr,所以你在32位变量中存储一个32位的值。根据您的计算机终端以及加载disp_addr的方式,您可能正在加载错误的数据。

您可能想要这样做:

disp_addr

这是不一样的。