Integer Promotion Trap in Bit-Shift Operation

本文探讨了位移运算中常见的陷阱,特别是将32位数据类型DWORD左移32位时出现的问题。通过对比不同的实现方式,揭示了正确处理位移运算的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

转载于:https://www.cnblogs.com/walfud/articles/3352243.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值