티스토리 뷰

The bitwise AND operation with 255 is really helpful in keeping the lowest 8 bits and remeoves the negaitive sign bits added during int conversion. 

For example, 
A C program in Embedded System is trying to send some data to external java program. 
C has uint8_t type, this type is 1byte and has value of 0~255 range. 

 
If the C program sent the 136 in binary, uini8_t type, java read this binary as -120. 
Because, if the leftmost bit of the full bits, java perceives it as negative. 

So, if you want to restore 120 to 136 that C program sent, you should perform bitwise AND operation. 
The process of this looks like below. 

byte receiveData = -120;
int unsignedInt = receiveData & 255; // 136



To go into detail in memory,


In here, you might have a question.
Why we perform bitwise AND operation with 255??

255 has eight 1s in binary, so AND operation with it keeps only the lowest 8 bits and removes the negative sign bits added during int conversion. 

In other words, we use "& 255" operation to see that number of 8 bits in 0~255 range.

( unsigned, not signed(-128 ~ 127) )

 

+) 

The sign is determined by the leftmost bit of the full type.

For byte (1byte),

0xxxxxxx → positive
1xxxxxxx → negative

 

For int (4byte),

0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx → positive
1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx → negative

 

 

 

----------------------

Tomorrow, I'm into My university's dormitory...!!!!!!!!

I'm super excited!!!!!!!!

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG more
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
글 보관함