Integer Promotion Trap in Bit-Shift Operation

Bug version:

    // FILETIME ft = ....;
    ULONGLONG res = ft.dwHighDateTime << 32 | ft.dwLowDateTime;                  // BUG, easy to find.

It's obvious that `DWORD` type has 32-bit width, `<< 32` will cause overflow. The result is 0 no matter `ft.dwHighDateTime` is.

 

Let's see a stable version:

    // FILETIME ft = ....;
    ULONGLONG res = (static_cast<ULONGLONG>(ft.dwHighDateTime) << 32) | ft.dwLowDateTime;   // OK.

The blue casting can solve the problem. It will force the `ft.dwHighDateTime` to be 64-bit, and shift the lower 32-bit to higher part, then, copy `dwLowDateTime` to lower part of 64-bit `dwHighDateTime`.

 

Oh, there must some one thinking a more "elegant" way to do the same thing, such as below:

    // FILETIME ft = ....;
    ULONGLONG res = (ft.dwHighDateTime << 32ull) | ft.dwLowDateTime;             // Seems elegant, but BUG.

 

Am, it seems better than the casting one, but think it more!

The `ull` in imperial red promote the 32-bit integer to 64-bit, let's parse the statement:

`ft.dwHighDateTime << 0x00000020`  =>  `ft.dwHighDateTime << 0x00000000, 00000020`.

You can notice, the right operand is expanded to 64-bit, which is bug prone!

The operation `<<` will not promote the left operand however there is overflow or 64-bit's right operand. Thus, (ft.dwHighDateTime << 32ull) == 0.

 

The conclusion is, bit-shift operation should expand LEFT operand first, and then to shift bit.

 

posted @ 2013-10-05 11:35  walfud  阅读(305)  评论(0编辑  收藏  举报