c++: 32位到64位迁移。

时间:2021-12-09 12:05:01

I am working on a project of migrating 32 bit C++ code to work on both 32 and 64-bit mode on Mac OS X. I am confused in certain things. For instance, consider the following lines of code-

我正在做一个迁移32位c++代码的项目,在Mac OS x上运行32位和64位模式。例如,考虑以下代码行。

long* buffer = new long[VAL];
long var = buffer[0];

Now, I know that sizeof(long) would return 4 in 32-bit and 8 in 64-bit. So, I am confused as to what should be the replacement for the above two lines in general so that these lines work correctly both in 32-bit as well as 64-bit mode.

现在,我知道sizeof(long)将在32位中返回4,在64位中返回8。因此,我很困惑,对于以上两行的替换应该是什么,这样这些行在32位和64位模式下都能正常工作。

This may sound like a trivial question but I am just no able to make any progress in such kind issues which are plentiful in the project I am working on.

这可能听起来是个微不足道的问题,但在我正在进行的项目中,我无法在此类问题上取得任何进展。

1 个解决方案

#1


2  

I am confused as to what should be the replacement for the above two lines in general so that these lines work correctly both in 32-bit as well as 64-bit mode.

我很困惑,对于这两行代码的替换应该是什么,这样这些行在32位和64位模式下都能正常工作。

The answer depends on what you mean by "working correctly".

答案取决于你所说的“正确工作”的意思。

If you are looking to use integers with specific size (i.e. 32 bits on all platforms or 64 bits on all platforms) use definitions from <cstdint>: int32_t for 32 bits, int64_t for 64 bits. This will ensure the exact sizing regardless of the platform.

如果您想要使用具有特定大小的整数(即所有平台上的32位或所有平台上的64位),请使用 : int32_t为32位,int64_t为64位的定义。这将确保无论平台的大小都是正确的。

If all you need is interoperability within your own program, you can leave everything as is: in the absence of overflows on the platform with the shortest long, the program is going to do the same thing on the platform with longer long, except that it would take more memory than is necessary.

如果你需要的是互操作性在自己的程序中,你可以把一切都是:没有溢出的平台上与长最短,程序会做同样的事情在平台时间长,除了需要更多的内存比是必要的。

#1


2  

I am confused as to what should be the replacement for the above two lines in general so that these lines work correctly both in 32-bit as well as 64-bit mode.

我很困惑,对于这两行代码的替换应该是什么,这样这些行在32位和64位模式下都能正常工作。

The answer depends on what you mean by "working correctly".

答案取决于你所说的“正确工作”的意思。

If you are looking to use integers with specific size (i.e. 32 bits on all platforms or 64 bits on all platforms) use definitions from <cstdint>: int32_t for 32 bits, int64_t for 64 bits. This will ensure the exact sizing regardless of the platform.

如果您想要使用具有特定大小的整数(即所有平台上的32位或所有平台上的64位),请使用 : int32_t为32位,int64_t为64位的定义。这将确保无论平台的大小都是正确的。

If all you need is interoperability within your own program, you can leave everything as is: in the absence of overflows on the platform with the shortest long, the program is going to do the same thing on the platform with longer long, except that it would take more memory than is necessary.

如果你需要的是互操作性在自己的程序中,你可以把一切都是:没有溢出的平台上与长最短,程序会做同样的事情在平台时间长,除了需要更多的内存比是必要的。