我只想把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);
我希望计时器等于1011,但我一直得到1作为输出。
最佳答案
这应该对你有用:
(你只需要知道诀窍)
#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
关于c - 将4个字符合并为一个无符号长,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27711735/