hi guys,
lets say I have:
int a = 22;
int b = 57;
and I want have
c= 2257;
to save space, I don't want to use string right.. so my idea was something like this:
int c;
c= (a << 16 | b);
and c will be then 2257 (it's hours and minutes btw) from DS3231
but my code is giving me that c = 1441849 after that
also tried
c = (a << 2 | b);
but c = 121
am I missing something?
Am I missing something?
Yes!
First int uses 16 bits, 22 and 57 only need 8 bits each, so byte or char or uint8_t will do.
Second, what is displayed as 22 is stored in binary as b00000000 00010110 (0x0016). When you shift it left 16 bits you get
b00010110 00000000 00000000(0x160000), which is 1441792 decimal.
Then you have 57 decimal, which is b00000000 00111001 (0x39)
OR the two and you get b00010110 00000000 00111001 (0x160039), which is 1441849 decimal.
In summary,
- Remember that numbers are stored in binary
- You've shifted left 16 bits when you only needed to shift 8
- Shifting won't work anyway for decimal numbers, well it will but not the way you are expecting
EDIT
If you look at the DS3231 data sheet you will see it doesn't store the time in simple binary, it uses binary coded decimal. So, for example 22:57 is stored as:
Minutes register (0x01) 0x57 (b0101 0111), which if you treat as binary would convert to 87 decimal
Hours register (0x02) 0x22 (b0010 0010), which if you treat as binary would convert to 34 decimal
I'm guessing you are using a library for the DS3231, which will hide the binary coded decimal from you.
@PerryBebbington - thanks a lot! now I understand it!!
@Deva_Rishi - omg.. that's really a new trick for me! good to know! 