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

Шиј*_*гор 3 c

我有一系列字符,如:

char bytes[8]={2,0,1,3,0,8,1,9}
Run Code Online (Sandbox Code Playgroud)

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

示例:从此数组中获取:年月日

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

int year = 2013 ......  month = 8 ............  day = 19
Run Code Online (Sandbox Code Playgroud)

md5*_*md5 6

你不应该用<<运算符左移(这或多或少相当于乘以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];
Run Code Online (Sandbox Code Playgroud)

当然,您可以使用循环来使代码更具可读性(如有必要).

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;
}
Run Code Online (Sandbox Code Playgroud)

使用最后一个代码,可以更轻松地更改存储日期的格式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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

19/08/2013
Run Code Online (Sandbox Code Playgroud)