Convert Little endian to Big endian in PHP or vice versa

In PHP you might have to convert the endianness of a number. PHP does not provide any function for this even though it has function for almost everything.

So I wrote a function for this,

function chbo($num) {
    $data = dechex($num);
    if (strlen($data) <= 2) {
        return $num;
    $u = unpack("H*", strrev(pack("H*", $data)));
    $f = hexdec($u[1]);
    return $f;


php > echo var_dump(5254071951610216, chbo(5254071951610216448));
php > echo var_dump(2147483648, chbo(2147483648));

Note: this function changes the byte order. If your machines byte-order is little-endian, this function will change it to big-endian. If your machines byte-order is big-endian, it will change the number to big-endian.

All x86 and x86_64 are little-endian. ARM can be both.  More can be found on this wiki article

Iterate through each valid calendar days

If you develop software like me, you may face a scenario where you need to iterate through calendar days.  These are specially needed in event management application or any other application that has some sorts of daily tracker. The main point is you want to iterate through dates.

For example, If the current date is “February 28th 2001”, next date will be  “March 1st 2001”. Obviously not “February 29th 2001”. If the current date is “February 28th 2004”, next date will be “February 29th 2004”, Not “March 1st 2004”.  Yes, that’s quite tricky.  So how do you achieve it in programming?

The solution is to use time function families found in standard C header file time.h. The main idea is to first create the time you want to show by mktime(). This is the initial time. To advance to the next day/hour/min/sec/month just convert the resultant value of mktime() to struct tm structure by localtime() or gmtime(). Then add 1 day/hour/min/sec/month to struct tm structure. Use this structure to create time again by mktime().

The above strategy works because of the following lines from manual.

     In addition to computing the calendar time, mktime() normal-
     izes  the  supplied tm structure. The original values of the
     tm_wday and tm_yday components of the structure are ignored,
     and the original values of the other components are not res-
     tricted to the ranges indicated in  the  definition  of  the

Here is a sample code that iterates through the first 200 dates from epoch.

#include <time.h>;
#include <stdio.h>;

int main(){
    struct tm *lt;
    int i=200;
    time_t t=1;  // first second on epoch

        lt = localtime(&t);
        printf("%s\n", asctime(lt));
        lt->tm_hour+=24; // adding 1 day = 24 hours
        t = mktime(lt);
    return 0;

If you are working with other language you may wonder if this will apply to your language. The good news is most language has wrapper for C routines.  May be the name is different. But  most probably you have it. Just see the manual.  Same technique will work on other language too.