LIGHT
LIGHT

Reputation: 5712

What does 0x0F mean? And what does this code mean?

I have this code. Please make me understand what does this code actually mean

  for(var i = 0; i < input.length; i++)
  {
    x = input.charCodeAt(i);
    output += hex_tab.charAt((x >>> 4) & 0x0F)
           +  hex_tab.charAt( x        & 0x0F);
  }

What is 0x0F? And, >>> Mean?

Upvotes: 9

Views: 68590

Answers (3)

Vivin Paliath
Vivin Paliath

Reputation: 95518

>>> is the unsigned bitwise right-shift operator. 0x0F is a hexadecimal number which equals 15 in decimal. It represents the lower four bits and translates the the bit-pattern 0000 1111. & is a bitwise AND operation.

(x >>> 4) & 0x0F gives you the upper nibble of a byte. So if you have 6A, you basically end up with 06:

6A = ((0110 1010 >>> 4) & 0x0F) = (0000 0110 & 0x0F) = (0000 0110 & 0000 1111) = 0000 0110 = 06

x & 0x0F gives you the lower nibble of the byte. So if you have 6A, you end up with 0A.

6A = (0110 1010 & 0x0F) = (0110 1010 & 0000 1111) = 0000 1010 = 0A

From what I can tell, it looks like it is summing up the values of the individual nibbles of all characters in a string, perhaps to create a checksum of some sort.

Upvotes: 21

Basic
Basic

Reputation: 26766

0x0f is a hexadecimal representation of a byte. Specifically, the bit pattern 00001111

It's taking the value of the character, shifting it 4 places to the right (>>> 4, it's an unsigned shift) and then performing a bit-wise AND with the pattern above - eg ignoring the left-most 4 bits resulting in a number 0-15.

Then it adds that number to the original character's right-most 4 bits (the 2nd & 0x0F without a shift), another 0-15 number.

Upvotes: 5

David G
David G

Reputation: 96810

0x0F is a number in hexadecimal. And >>> is the bitwise right-shift operator.

Upvotes: 1

Related Questions