Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 546
LIGHT Avatar asked Oct 20 '12 15:10

LIGHT


2 Answers

>>> 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.

like image 139
Vivin Paliath Avatar answered Sep 24 '22 14:09

Vivin Paliath


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.

like image 25
Basic Avatar answered Sep 20 '22 14:09

Basic