Using bitwise operators

后端 未结 12 1655
既然无缘
既然无缘 2021-01-06 08:21

I\'ve been studying C# and ran accross some familiar ground from my old work in C++. I never understood the reason for bitwise operators in a real application. I\'ve never u

12条回答
  •  走了就别回头了
    2021-01-06 08:45

    An example from COM programming:

    An HRESULT is an error code consisting of a 32 bit integer. The high bit is a flag indicating whether the code represents success (0) or failure (1). The next 15 bits are an integer representing what sort of error it is -- an ole automation error or a win32 error or whatever. The lower 16 bits are the actual error code.

    Being able to shift bits around is quite useful when you want to get information into or out of an HRESULT.

    Now, you almost always want to abstract away the bit twiddling. It's much better to have a method (or in C, a macro) that tells you whether the HRESULT is failure, rather than actually twiddling out the bit with (hr & 0x80000000) != 0 right there in your source code. Let the compiler inline it.

    There are lots of examples of low-level data structures where information is crammed into words and needs to be extracted with bitwise operations.

提交回复
热议问题