0

I'm trying to convert an int to a 4 byte unsigned ints. I was reading a post and I'm not sure what comparison does. I know that its a sub mask, but I'm not sure when to use the & and when to use the |. Lets use the number 6 as an example, if the LSB is the number 6. Why would we do

6 & 0xFF// I know that we are comparing it to 11111111 

when do we use the OR operator? I'm still not sure how to use the & nor |

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
azureskys
  • 13
  • 6

1 Answers1

0

x & 0xFF will set all bits of x to zero except for the last byte (which stays the same). If you had used a bitwise or (|), it would leave the bits of x set, and set all the bits of the last byte to 1.

Typically, the comparison will be something like (x & 0xFF) == x. This is to make sure that the first three bytes of x are all 0.

Red Alert
  • 3,786
  • 2
  • 17
  • 24
  • No, if you want to mask the last three BITS, you'd have to do 0x07 (binary 00000111). To mask the last three bytes, you can use 0xFFFFFF. – Red Alert Mar 10 '14 at 21:55
  • What if I only wanted the second byte? – azureskys Mar 10 '14 at 21:59
  • Each `FF` is equivalent to one byte of all 1s. An integer is 32 bits - so all 0s would be `0x00000000`, and all 1s would be `0xFFFFFFFF`. To zero everything except the second byte, you can do `x & 0x00FF0000`. If you want to store that in an 8 bit structure like a `char` or `byte`, you can do something like `char y = x & 0x00FF0000 >>> 16`. This shifts the second byte of x into the last byte position` – Red Alert Mar 10 '14 at 22:04
  • What would I do if I wanted to decode it? I would read it, then store it into a char then I shift it the amount of spaces back to the original. But how would I combine the 4 bytes back into an int? – azureskys Mar 10 '14 at 22:43
  • you just do the opposite, `int x = y << 16`. that will set the second byte back. If you have the first byte stored in `z`, you could follow up with `x |= z << 24`. Using the bitwise or lets you set one byte without affecting the others. – Red Alert Mar 10 '14 at 22:54