Extract data with bitwise and bitwise operators

2

Well, I'm having some trouble separating parts of the date 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 do print for example of year1 it has nothing to do with date year 1. I think I am making confusion because the dates are in base 10 and the mask is in base 16

    
asked by anonymous 29.11.2015 / 12:59

1 answer

1

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

The only way to ensure that you understand how to extract certain sets of bits from an integer is doing just the opposite: implement a function to compact the date into an integer :

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 counter bitshift operators and refresh the bitmasks that are used with the bitwise & :

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

    // ...
}
    
03.12.2015 / 01:12