演算子で左シフトする<<
(これは を乗算するのとほぼ同等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