Extract data with bitshift and bitwise operators

Asked

Viewed 77 times

2

Good, I’m having some trouble separating the date parts through bitwise operations.

date format: yyyy-dd-mm

int menor_data(int date1, int date2)
{    
    int day1 = (date1 >> 8) & 0xff;
    int month1 = date1 & 0xff;
    int year1 = (date1 >> 16) & 0xff;
    int day2 = (date2 >> 8) & 0xff;
    int month2 = date2 & 0xff;
    int year2 = (date2 >> 16) & 0xff;
}

The problem is that when I print for example Year1 has nothing to do with the date year 1. I think I’m making a mess because the dates are based on 10 and the mask is based on 16

  • 2

    Please show a full example that includes the entries you pass to the function menor_data (beyond the result obtained and the expected)

1 answer

1

There are several problems in your code. The main one is the order of use of operators of bitwise and operators of bitshift that are reversed.

The only way to ensure that you understand how to extract certain bit sets from an integer is by doing just the opposite: implement a function to compress the date into an integer number:

int gerar_data(char dia, char mes, short int ano) 
{
    int y_d_m = 0; // yyyyddmm
    y_d_m |= (ano & 0xFFFF) << 16;
    y_d_m |= (dia & 0xFF) << 8;
    y_d_m |= (mes & 0xFF) ;

    //printf("ydm = %d\n", y_d_m );
    return y_d_m ;
}

Now the second part of the problem is solved more easily: just use opposite operators of bitshift and update the bit masks that are used with the operator bitwise &:

int menor_data(int date1, int date2)
{    
    int year1  = (date1 & 0xFFFF0000) >> 16;
    int day1   = (date1 & 0xFF00) >> 8;
    int month1 = (date1 & 0xFF);

    // ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.