In the following code:
short = ((byte2 << 8) | (byte1 & 0xFF))
What is the purpose of &0xFF?
Because other somestimes I see it written as:
short = ((byte2 << 8) | byte1)
And that seems to work fine too?
Join Stack Overflow to learn, share knowledge, and build your career.
|
In the following code:
What is the purpose of
And that seems to work fine too? |
|||
|
Anding an integer with See |
||||
|
|
|
if
|
|||
|
|
|
The danger of the second expression comes if the type of
will print
I tried it on gcc v3.4.6 on Solaris SPARC 64 bit and the result is the same with TL;DR The masking is to avoid implicit sign extension. EDIT: I checked, it's the same behaviour in C++. |
|||||
|
|
Assuming your So Say If byte1 is of some other type say integer of 4 bytes, bitwise AND with 0xFF leaves you with least significant byte(8 bits) of the byte1. |
||||
|
|
|
The if If |
|||||
|
|
it clears the all the bits that are not in the first byte |
|||
|
|
|
If the result ends up greater than |
|||
|
|
uint8_t? – Shahbaz Feb 5 '13 at 17:17byte1, which seems quite likely becausebyte2already is not 8-bits (otherwisebyte2 << 8is 0) – Shahbaz Feb 5 '13 at 17:33byte2 << 8works even ifbyte2is an 8 bit type. By default expressions always work asint. The compiler sees implicitly the expression as((int)byte2) << ((int)8)– Patrick Schlüter Feb 5 '13 at 17:40shortis a reserved word and can not be used as variable name. – Patrick Schlüter Feb 5 '13 at 17:46