- 论坛徽章:
- 0
|
原帖由 pagx 于 2009-12-9 12:57 发表
sizeof(0xFF ) == 4
sizeof('\xFF') == 1
实质上 0xFF 只是 255 的另外一种表示方式。
int n = (char)0xff;
其实是被解析成 int n = (int)((char)((int)0xFF));
所以在 int 往 char 赋值时, 被截断, ...
说的有道理,测试如下:
[wpc_LK@localhost test]$ g++ -v
使用内建 specs。
目标:i686-redhat-linux
配置为:
线程模型:posix
gcc 版本 4.4.2 20091027 (Red Hat 4.4.2-7) (GCC)
[wpc_LK@localhost test]$ cat test.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[]) {
int n = (char)0xff;
cout << "int: (char)0xff : " << n << endl;
n = (unsigned char)0xff;
cout << "int: (unsigned char)0xff : " << n << endl;
short m = (char)0xff;
cout << "short: (char)0xff : " << m << endl;
m = (unsigned char)0xff;
cout << "short: (unsigned char)0xff : " << m << endl;
long l = (char)0xff;
cout << "long: (char)0xff : " << l << endl;
l = (unsigned char)0xff;
cout << "long: (unsigned char)0xff : " << l << endl;
return EXIT_SUCCESS;
}
[wpc_LK@localhost test]$ ./test
int: (char)0xff : -1
int: (unsigned char)0xff : 255
short: (char)0xff : -1
short: (unsigned char)0xff : 255
long: (char)0xff : -1
long: (unsigned char)0xff : 255
[wpc_LK@localhost test]$ |
|