将4个字符组合成一个无符号长字符

时间:2014-12-30 19:59:40

标签: c microcontroller mplab

我只想将4个字符组合成一个无符号长变量,如下所示。

char y[16];
unsigned long Timer ;

y[12] = '1' ;
y[13] = '0' ;
y[14] = '1' ;
y[15] = '1' ; 
Timer  =   y[15] - '0' ;
Timer |=  (unsigned long) (y[12] - '0' << 24);
Timer |=  (unsigned long) (y[13] - '0'  << 16);
Timer |=  (unsigned long) (y[14] - '0'  << 8);

printf("%lu" , Timer);

我希望Timer等于 1011 ,但我一直将 1 作为输出。

1 个答案:

答案 0 :(得分:3)

这应该适合你:

(你只需知道技巧)

#include <stdio.h>

int main() {

    char y[16];
    unsigned long Timer ;

    y[12] = '1';
    y[13] = '0';
    y[14] = '1';
    y[15] = '1';

    Timer = y[12] - '0';  //- '0' To get the digit, here 1, and this for every digit
    Timer = (Timer * 10) + y[13] - '0';  //*10 to make place for the next digit, and this for every digit (expect the 1st one)
    Timer = (Timer * 10) + y[14] - '0';
    Timer = (Timer * 10) + y[15] - '0';

    printf("%lu" , Timer);

    return 0;

}

输出:

1011