2

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

asked Jun 12, 2020 at 2:36
1
  • how many bits long is eeaddress? Commented Jun 12, 2020 at 4:24

1 Answer 1

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
answered Jun 12, 2020 at 8:14
6
  • Do you also know why there is an int cast ((int)...)? Commented Jun 12, 2020 at 11:34
  • @Gerben; actually I would either expect a 8 bit type cast (uint8_t or int8_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. Commented Jun 12, 2020 at 11:53
  • 1
    Thank you. Seems like the Wire library will cast it (back) into an uint8_t anyways. Commented Jun 12, 2020 at 18:40
  • @Gerben, true, thus casting it within the calling write method is not needed. Commented Jun 12, 2020 at 19:01
  • Thanks @Michel Keijzers Commented Jun 16, 2020 at 16:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.