In the following code:
short = ((byte2 << 8) | (byte1 & 0xFF))
What is the purpose of & 0xFF? Because sometimes, I see the above code written as:
short = ((byte2 << 8) | byte1)
And that seems to work fine too.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Anding an integer with
0xFFleaves only the least significant byte. For example, to get the first byte in ashort s, you can writes & 0xFF. This is typically referred to as “masking”. Ifbyte1is either a single byte type (likeuint8_t) or is already less than 256 (and as a result is all zeroes except for the least significant byte) there is no need to mask out the higher bits, as they are already zero.See
tristopiaPatrick Schlüter’s answer below when you may be working with signed types. When doing bitwise operations, I recommend working only with unsigned types.