Machado
Machado

Reputation: 14499

How can I invert this bit operation?

Well this is probably very easy but I'm stuck.

I'm working with a 16 bit sized long variable which holds the value of the current hour and minute.

0000 1000 0011 1111

Please note:

The first 4 bits are useless;

The last 6 bits are the hours, and the remaining represents the minutes;

There is no way to change this variable type or size;

And this is how I successfully get the hours and minutes:

hour = ((int) original_value >> 6) & 0x1F;
minute = ( (int) original_value ) & 0x3F;

How can I reverse this operation to create new original_value with different hours and minutes?

Upvotes: 0

Views: 108

Answers (1)

Sean Bright
Sean Bright

Reputation: 120714

I might be missing something, but this should do the trick:

new_value = (new_hour << 6) | (new_minutes & 0x3f);

Although as others have pointed out, the way you are extracting hour is probably wrong, you should be ANDing with 0x3F, not 0x1F:

hour = ((int) original_value >> 6) & 0x3F;

Upvotes: 5

Related Questions