i have took below code from https://lastminuteengineers.com/ds1307-rtc-arduino-tutorial/. i am not understand what these codes are doing. please help me to understand.
Wire.write((int)(eeaddress >> 8)); // MSB
Wire.write((int)(eeaddress & 0xFF)); // LSB
Thanks
1 Answer 1
These two lines write a 16 bit (2 8-bit) value, which is signed -32768..32767 or unsigned 0..65535.
Assume a value in bits: 10101010 11001100
Statement 1:
Wire.write((int)(eeaddress >> 8)); // MSB
The first statement shifts the value 8 bits (positions) to the right; this is called the MSB (Most Significant Byte, the left 8 bits). Bits on the right are clipped / fall off. Thus
10101010 11001100
will become
00000000 10101010
When casted to an 8 bit value you get:
10101010
Statement 2:
Wire.write((int)(eeaddress & 0xFF)); // LSB
The second statement will get the LSB (Least Significant Byte). This used the AND operator, meaning a bit is only 1 if both values are 1. 0xFF is the 'mask'
Original value: 10101010 11001100
Mask: 00000000 11111111
----------------- AND (&) operator
Result: 00000000 11001100
As you can see only the right 8 bits are kept. When casting this to an 8 bit value:
11001100
-
Do you also know why there is an int cast (
(int)...
)?Gerben– Gerben2020年06月12日 11:34:08 +00:00Commented Jun 12, 2020 at 11:34 -
@Gerben; actually I would either expect a 8 bit type cast (
uint8_t
orint8_t
cast as the result is always 8 bits, or no cast at all, as the caller probably expects an 8 bit variable. Even if the caller expects 16 bit (which would be unnecessary much), the 8 bit argument will automatically be casted to 16 bits, without a need for a cast in the two lines provided in this code.Michel Keijzers– Michel Keijzers2020年06月12日 11:53:03 +00:00Commented Jun 12, 2020 at 11:53 -
1Thank you. Seems like the Wire library will cast it (back) into an uint8_t anyways.Gerben– Gerben2020年06月12日 18:40:11 +00:00Commented Jun 12, 2020 at 18:40
-
@Gerben, true, thus casting it within the calling
write
method is not needed.Michel Keijzers– Michel Keijzers2020年06月12日 19:01:07 +00:00Commented Jun 12, 2020 at 19:01 -
Thanks @Michel KeijzersSuman Ponmathan– Suman Ponmathan2020年06月16日 16:59:44 +00:00Commented Jun 16, 2020 at 16:59
eeaddress
?