0

In Java script I want to extract bits 13 to 16 from integer number. Example: If I extract bits 13 to 16 from number 16640 then output will be 2

I have searched on google and found few links but they are in C language.

Community
  • 1
  • 1
Hitesh
  • 3
  • 3

3 Answers3

2

Assuming your bit count starts at 0:

var extracted, orig;

orig = parseInt("16640", 10); // best practice on using parseInt: specify number base to avoid spurious octal interpretation on leading zeroes (thx Ken Fyrstenberg)
extracted = ((orig & ((1 << 16) - 1) & ~(((1 << 13) - 1))) >>> 13);

Explanation:

  • mask the lower 16 bits of the original number
  • mask the complement of the lower 13 bits of the result (ie. bits 13-31)
  • you currently have bits 13-16 of the orignal number in their original position. shift this bit pattern 13 bits to the right.

Note that this method only works reliably for numbers less than 2^31. The docs (MDN) are here

collapsar
  • 17,010
  • 4
  • 35
  • 61
  • Upvoted, but just remember to specify base for parseInt or you could end up with parsing octals if the number has a leading 0 etc. (`parseInt(str, 10);`) –  Mar 17 '15 at 11:35
  • @KenFyrstenberg Thank you, merged your hint into the answer. – collapsar Mar 17 '15 at 12:31
2

Javascript's bitwise operations work essentially the same way as they do in C:

var bits13to16 = (number >> 13) & 15;

This shifts the number 13 bits to the right (eliminating bits 0-12) and masks all but the last 4 remaining bits (which used to be bits 13-16). 15 = 2^4 - 1.

radiaph
  • 4,001
  • 1
  • 16
  • 19
0

All suggestions are working but the simplest I think is given by @dandavis.

parseInt( 16640 .toString(2).slice(-16, -13), 2 );

Hitesh
  • 3
  • 3