http://www.cmykrgb123.cn/blog/
在C/C++中,64為整型一直是一種沒有確定規(guī)范的數(shù)據(jù)類型?,F(xiàn)今主流的編譯器中,對64為整型的支持也是標準不一,形態(tài)各異。一般來說,64位整型的定義方式有l(wèi)ong long和__int64兩種(VC還支持_int64),而輸出到標準輸出方式有printf(”%lld”,a),printf(”%I64d”,a),和cout << a三種方式。
本文討論的是五種常用的C/C++編譯器對64位整型的支持,這五種編譯器分別是gcc(mingw32),g++(mingw32),gcc(linux i386),g++(linux i386),Microsoft Visual C++ 6.0。可惜的是,沒有一種定義和輸出方式組合,同時兼容這五種編譯器。為徹底弄清不同編譯器對64位整型,我寫了程序對它們進行了評測,結果如下表。
| 變量定義 |
輸出方式 |
gcc(mingw32) |
g++(mingw32) |
gcc(linux i386) |
g++(linux i386) |
MicrosoftVisual C++ 6.0 |
| long long |
“%lld” |
錯誤 |
錯誤 |
正確 |
正確 |
無法編譯 |
| long long |
“%I64d” |
正確 |
正確 |
錯誤 |
錯誤 |
無法編譯 |
| __int64 |
“lld” |
錯誤 |
錯誤 |
無法編譯 |
無法編譯 |
錯誤 |
| __int64 |
“%I64d” |
正確 |
正確 |
無法編譯 |
無法編譯 |
正確 |
| long long |
cout |
非C++ |
正確 |
非C++ |
正確 |
無法編譯 |
| __int64 |
cout |
非C++ |
正確 |
非C++ |
無法編譯 |
無法編譯 |
| long long |
printint64() |
正確 |
正確 |
正確 |
正確 |
無法編譯 |
上表中,正確指編譯通過,運行完全正確;錯誤指編譯雖然通過,但運行結果有誤;無法編譯指編譯器根本不能編譯完成。觀察上表,我們可以發(fā)現(xiàn)以下幾點:
- long long定義方式可以用于gcc/g++,不受平臺限制,但不能用于VC6.0。
- __int64是Win32平臺編譯器64位長整型的定義方式,不能用于Linux。
- “%lld”用于Linux i386平臺編譯器,”%I64d”用于Win32平臺編譯器。
- cout只能用于C++編譯,在VC6.0中,cout不支持64位長整型。
表中最后一行輸出方式中的printint64()是我自己寫的一個函數(shù),可以看出,它的兼容性要好于其他所有的輸出方式,它是一段這樣的代碼:
void printint64(long long a)
{
if (a<=100000000)
printf("%d\n",a);
else
{
printf("%d",a/100000000);
printf("%08d\n",a%100000000);
}
}
這種寫法的本質是把較大的64位整型拆分為兩個32位整型,然后依次輸出,低位的部分要補0。
部分編譯錯誤"warning: integer constant is too large for 'long' type"疑問描述
Keywords: EDK, long long integer, 64-bit, SW, mb-gcc, powerpc-eabi-gcc, compiler, C/C++ , g++
When I define a long long integer data type in SW application in EDK, a warning / error similar to the following occurs:
"warning: integer constant is too large for 'long' type".
Example:
int main ()
{
long long int test = 0x0008888000000000;
},
解決方案
The warning message can be safely ignored, as mb-gcc is not doing anything wrong; the 64-bit computing is in fact correct.
This warning occurs because gcc is strict in syntax and requires LL on the end of such constants. This warning message disappears if the integer is appended with LL.
long long int test = 0x0008888000000000LL;