不要使用“<<”操作符进行左移(它大体上等同于将其乘以“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
char
就是char
,没有别的。 - user529758char
是一种整型,它可以隐式地转换为其他整型,但这并不意味着"char
是一个unsigned int
",因为它不是。 - user529758