使用按位运算从int日期中提取月份(yyyyMMdd) [英] using bitwise operation to extract month from int date (yyyyMMdd)

查看:85
本文介绍了使用按位运算从int日期中提取月份(yyyyMMdd)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用按位运算符从以 int (格式为YYYYMMDD,例如20110401)表示的日期中提取月份?

Is it possible to extract the month from date represented as int (format YYYYMMDD, e.g. 20110401) using some bitwise operators?

如果是这样,怎么办?

我目前正在使用20110401%10000/100.我认为按位操作可能会更快.DateTime.Parse等对于我想做的事情来说太慢了.

edit: I am currently using 20110401 % 10000 / 100. I thought bit-wise could be faster. DateTime.Parse etc. are too slow for what I am trying to do.

推荐答案

如果您以二进制格式表示日期,则可以按位操作有效地提取月份,例如,每天5位月份中的4位,月份号中的4位,年份中的其余部分,而不是十进制数字.对于您的示例,日期将为(2011<< 9)+(4<< 5)+1(当然不等于20110401).要使用按位运算从此类表示中提取字段,请执行以下操作:

You could efficiently extract the month with bitwise operations if you represented the date in a binary format, e.g., 5 bits for the day of the month, 4 bits for the month number, and the rest for the year, rather than as decimal digits. For your example, the date would be (2011 << 9) + (4 << 5) + 1 (which of course is not equal to 20110401). To use bitwise operations to extract the fields from such a representation:

int year = date >> 9;
int month = (date >> 5) & 0xF;
int day = date & 0x1F;

马克·拜尔斯(Mark Byers)提到的另一种方法是使用结构,例如,

Another approach, as mentioned by Mark Byers, is to use a struct, e.g.,

typedef struct {
    short year;
    char  month;
    char  day;
} Date;

您可以将它们传递到堆栈上,按名称提取字段,并将其初始化为

You can pass these around on the stack, extract the fields by name, and initialize them as

Date d = { 2011, 4, 1};

或者在C99中,

Date d = { .year = 2011, .month = 4, .day = 1 };

这篇关于使用按位运算从int日期中提取月份(yyyyMMdd)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆