c语言中,怎样把内容为数字的unsigned char转换为int?

我定义了uchar buf = '1152'; int num; 怎样通过转换使得num = buf中的数值1152?

polly@nowthen:~$ cat test.c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>

int main(int argc, char *argv[])
{
           int base;
           char *endptr, *str;
           long val;

           if (argc < 2) {
               fprintf(stderr, "Usage: %s str [base]\n", argv[0]);
               exit(EXIT_FAILURE);
           }

           str = argv[1];
           base = (argc > 2) ? atoi(argv[2]) : 10;

           errno = 0;    
           val = strtol(str, &endptr, base); <----------关键

           if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
                   || (errno != 0 && val == 0)) {
               perror("strtol");
               exit(EXIT_FAILURE);
           }

           if (endptr == str) {
               fprintf(stderr, "No digits were found\n");
               exit(EXIT_FAILURE);
           }

           printf("strtol() returned %ld\n", val);

           if (*endptr != '\0')        
               printf("Further characters after number: %s\n", endptr);

           exit(EXIT_SUCCESS);
}
polly@nowthen:~$ gcc -Wall test.c -o liu
polly@nowthen:~$ ./liu 1152
strtol() returned 1152
polly@nowthen:~$ ./liu '1152'
strtol() returned 1152

温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-07-14
num = (int)buf ;
相似回答