3

次のような文字の配列があります。

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

以下のこの配列から最初の 4 文字を取得し、それらを新しい整数変数に入れたいと思います。これどうやってするの?それらをシフトしようとしていますが、このロジックは機能していません。何か案が?ありがとう。

例: この配列から取得する: 年月日

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

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

6 に答える 6

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];

もちろん、ループを使用してコードを読みやすくすることもできます (必要な場合)。

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
于 2013-08-19T18:43:12.470 に答える