c - C语言从char数组中获取int值

标签 c

我有一个字符数组,例如:

char bytes[8]={2,0,1,3,0,8,1,9}

我想从下面这个数组中取出前四个字符,并将它们放入一个新的整型变量中。我怎样才能做到这一点?我试图改变它们,但这种逻辑不起作用。任何的想法?谢谢。

例子:从这个数组得到:年月日

char bytes[8]={2,0,1,3,0,8,1,9}

int year = 2013 ......  month = 8 ............  day = 19

最佳答案

而不是左移 <<运算符(或多或少等同于乘以 2^N ),您应该乘以 10^N .以下是您可以执行的操作:

int year = bytes[0] * 1000 +
           bytes[1] * 100 +
           bytes[2] * 10 +
           bytes[3];

int month = bytes[4] * 10 +
            bytes[5];

int day = bytes[6] * 10 +
          bytes[7];

当然,您可以使用循环来使您的代码更具可读性(如果需要)。

enum {
   NB_DIGITS_YEAR = 4,
   NB_DIGITS_MONTH = 2,
   NB_DIGITS_DAY = 2,
   DATE_SIZE = NB_DIGITS_YEAR + NB_DIGITS_MONTH + NB_DIGITS_DAY
};

struct Date {
   int year, month, day;
};

int getDateElement(char *bytes, int offset, int size) {
   int power = 1;
   int element = 0;
   int i;

   for (i = size - 1; i >= 0; i--) {
      element += bytes[i + offset] * power;
      power *= 10;
   }

   return element;
}

struct Date getDate(char *bytes) {
   struct Date result;
   result.year = getDateElement(bytes, 0, NB_DIGITS_YEAR);
   result.month = getDateElement(bytes, NB_DIGITS_YEAR, NB_DIGITS_MONTH);
   result.day = getDateElement(bytes, NB_DIGITS_YEAR + NB_DIGITS_MONTH, NB_DIGITS_DAY);
   return result;
}

使用最后一段代码可以更轻松地更改存储在 bytes 中的日期格式.

例子:

int main(void) {
   char bytes[DATE_SIZE] = {2, 0, 1, 3, 0, 8, 1, 9};
   struct Date result = getDate(bytes);
   printf("%02d/%02d/%04d\n", result.day, result.month, result.year);
   return 0;
}

输出:

19/08/2013

关于c - C语言从char数组中获取int值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18320745/

相关文章:

c - 如何协调被 Getasynckeystate 阻止的 Sendmessage、SendInput、Mouse_event?

c - 了解 C 中的线程

c - 在代码片段 1 中发现段错误,但在代码片段 2 中未发现,两者的实现方式类似

c - 与 Posix 信号量同步线程

使用 C 将 ppm 文件从 P3 转换为 P6

c - Windbg条件断点不会断?

c - 为什么 if( union member) 评估为 True?

c - 如何正确识别C中的不同行尾?

C: 分配给 char... 期待类型转换?

c - putch() 和 putchar() 有什么区别?