我想把两个字节合并成一个无符号的长变量,我当前的代码不起作用。我正在使用MPLABC18编译器,这是我的代码。

    unsigned long red = 0;
    BYTE t[2];


    t[0]  = 0x12;
    t[1]  = 0x33;

    red = 100 * t[0] + t[1];
    printf("%lu", red);

请告诉我为什么我没有得到1233作为我的输出。

最佳答案

您会注意到数组中的值是用0x前缀指定的。100不等于0x100
您的编译器不兼容。此外,二进制运算符对有符号整数类型的定义很差,其中BYTE可能是。为了安全起见,下面是我编写代码的方法:

unsigned long red = 0;
BYTE t[2];

t[0]  = 0x12;
t[1]  = 0x33;

red = (unsigned char) t[0];
red = red * 0x100;
red = red + (unsigned char) t[1];

printf("Decimal: %lu\n"
       "Hexadecimal: 0x%lx\n", red, red);

关于c - 如何将两个字节数组转换为无符号长变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17052144/

10-12 14:58
查看更多