Library tutorials & articles

Typical errors of porting C++ code on the 64-bit platform

Bit shifting operations

Bit shifting operations can cause a lot of troubles during the port from the 32-bit system on the 64-bit one if used inattentively. Let’s begin with an example of a function which defines the bit you’ve chosen as 1 in a variable of memsize type.

ptrdiff_t SetBitN(ptrdiff_t value, unsigned bitNum) {
  ptrdiff_t mask = 1 << bitNum;
  return value | mask;
}

The given code works only on the 32-bit architecture and allows to define bits with numbers from 0 to 31. After the program port on the 64-bit platform it becomes necessary to define bits from 0 to 63. What do you think which value will the following call of SetBitN(0, 32) function return? If you think that 0x100000000 the authors is glad because he hasn’t prepared this article in vain. You’ll get 0.

Pay attention that "1" has int type and during the shift on 32 positions an overflow will occur. To correct the code it is necessary to make the constant "1" of the same type as the variable mask.

ptrdiff_t mask = ptrdiff_t(1) << bitNum;
or
ptrdiff_t mask = CONST3264(1) << bitNum;

Comments

  1. 01 Jan 1999 at 00:00

Leave a comment

Sign in or Join us (it's free).

Andrey Karpov
AddThis

Related podcasts

  • Interview with Shawn Burke on Microsoft's .NET Source Code Release

    Scott and Carl talk with Shawn Burke on the culmination of his many-year-old plan to get parts of the source of the .NET Framework released. With Visual Studio 2008, a simple process will allow developers to STEP INTO the .NET Framework Source from the IDE. This'll be a great debugging and learni...

We'd love to hear what you think! Submit ideas or give us feedback