Search code examples
syntaxbit-manipulationbit

What is the "0xXXXX" syntax when learning bit manipulation? (where X is a capital alphanumeric character)


I'm trying to learn about bit manipulation by doing a few problems after learning the basics and in some solutions, I seem to see this format. For example:

N = (N & 0xAAAA)>>1 | (N & 0x5555)<<1

What does this do (specifically the 0XAAAA and 0x5555)? And what is the name of this syntax or format so that I can look it up?

Thanks


Solution

  • Those are hexadecimal values. The 0xAAAA is equivalent to 1010101010101010. A = 1010 (in binary). So therefore 4 A's is four sequences of the binary value.

    When you combine that with a binary &, you look for all the bits of N that coincide with the pattern 1010... where both bits are 1 and keep those bits only.

    Example:

      1110101010101001
    & 1010101010101010
    ------------------
      1010101010101000
    

    The same goes for the 0x5555. 5 = 0101. Hopefully you get the idea.

    The binary or operator on the other hand returns a 1 in every place where the binary numbers have a 1, as in:

      1010
    | 0101
    ------
      1111
    

    The bit shift operators ( >> and << ) move each binary digit one place over (depending on the direction of the arrows) and so on. The hex is just a nicer format to visualize the bits without having to write out every single bit.