-1

I ran across an online explanation of what masking is with respect to bitwise operators, but was unable to fully understand the explanation due to the use of symbols that I'm not familiar with. Here is the demonstration:

enter image description here

The specific line that confuses me is "// Actual shift is 10 & (8-1) = 2 ". I get that 10 is the number of bits that we want to shift left by, but what does "&" mean in this context, and why do we subtract 8-1?

Link to the demonstration can be found here:

https://msdn.microsoft.com/en-us/library/8xftzc7e(v=vs.100).aspx

Thanks in advance.

SolarCalf
  • 31
  • 6
  • 1
    Please do not paste code as an image, use the proper embedding instead. – jontro Oct 12 '17 at 22:53
  • 2
    (See [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/a/285557/14122) for rationale -- searchability/indexing, robustness against broken links, and accessibility for people using assistive technologies are among the reasons to prefer that content be posted as text). – Charles Duffy Oct 12 '17 at 22:57

1 Answers1

0

The answer is in the second paragraph of your own links remark section

The << operator masks expression2 to avoid shifting expression1 by too much. Otherwise, if the shift amount exceeded the number of bits in the data type of expression1, all the original bits would be shifted away to give a trivial result. To ensure that each shift leaves at least one of the original bits, the shift operators use the following formula to calculate the actual shift amount: mask expression2 (using the bitwise AND operator) with one less than the number of bits in expression1.

Number of bits in a byte is 8. So the bitmask is 7, or 0b111. Apply this to 10 (0x1010) you arrive at 0x10 aka 2. That’s your shift amount.

deets
  • 6,285
  • 29
  • 28
  • 2
    The JScript `<<` doesn't seem to actually put rotated out bits back on the right, though, it just changes a shift by 10 on a byte to a shift by 2. IMO it's dubious language design... – Imperishable Night Oct 12 '17 at 23:07
  • Who uses JScript these days anyhow? Maybe the OP is just reading some outdated unrelated documentation – jontro Oct 12 '17 at 23:15
  • @ImperishableNight consider my face palmed. – deets Oct 12 '17 at 23:44
  • @ImperishableNight that's really common. Rotate semantics for shifts are rare. – harold Oct 13 '17 at 07:41
  • @harold The program with the JScript semantic is, as a programmer, if I want to shift all the bits away from a byte, I probably have a good reason to do so. "255" is almost never a logical continuation of "255, 127, 63, 31, 15, 7, 3, 1, _". – Imperishable Night Oct 13 '17 at 21:51