Explain the following C++ method

偶尔善良 提交于 2019-12-02 03:28:30

In C++, just like most programming languages, you can only return one value. To "return" two values, it's a common C/C++ practice to return one and pass a pointer to an object and modify that object via the pointer (mask in this case).

The object that mask point to will be assigned a bitmask with exactly one bit set. This is done be taking the hexadecimal value 0x80 (1000 0000 in binary form) and right shift it 0 to 7 steps. The exact number of steps is decided by x, which is computer using some application-specific logic.

The value returned is the x / 8.

You can see the routine as a division routine that returns x/8 and the remainder (like x modulo 8, but expressed as a bit mask rather than an integer value).

The last two lines are bit shifting.

mask is taking 0x80 and shifting it (x to the mod of 8) positions eg 5 >> 2 will give you 1.

x >> 3 is as it says, dividing it by 8, its taking x and moving all the bits 3 positions to the right (so thats 1,2,4), as a result, 8 will become 1 etc. its a little like integer div, but would be faster (as the comment says, fast divide by 8)

  *mask = (char)(0x80 >> (x % 8));  

The value x is masked so that only the lower three bits remain. The value 0x80 is shifted to right by the remaining number. The result is assigned to the value where mask points to.

   return (int)(x >> 3);    // fast divide by 8     

x is divided by eight. The result is the reutrn value of the method.

>> is right shift operator.

for e.g 8 > 3 will give you 1, right shift binary value of 8 by 3 places

1000(binary of 8) right shift by 3 places = 0001 (1 in decimal)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!