java 中char当然是占2个字节,16位。
char在C和C+中占一个字节
Java中无论是汉字还是英文字母都是用Unicode编码来表示的,一个Unicode码是16位,每字节是8位,所以一个Unicode码占两字节。但是英文字母比较特殊,源自于8位(1字节)的ASCII吗,于是在Unicode码仅使用了低8位(1字节)就可以表示,高8位的话不使用也无所谓。所以
char c='a';
System.out.println(c.getBytes().lenth()),得到的是1(字节)
但汉字就完整地使用了16位(2字节)的Unicode,所以
char c='中';
System.out.println(c.getBytes().lenth()),得到的是2(字节)
我在codeblocks 的 C语言当中输入如下代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c = '中';
printf("%c",c);
return 0;
}
报出两个警告
D:\codeblocks\fasd\main.c|7|warning: multi-character character constant|
D:\codeblocks\fasd\main.c|7|warning: overflow in implicit constant conversion|
||=== Build finished: 0 errors, 2 warnings ===|
说明中 这个字占了两个字节,而c只是分配了1个字节 造成不能正常输出
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c[2] = "中";
printf("%s",c);
return 0;
}
这样的话就正常输出了
C++程序
#include <iostream>
using namespace std;
int main()
{
char c = '中';
cout <<c<< endl;
return 0;
}
仍然报出警告
#include <iostream>
using namespace std;
int main()
{
char c[] = "中";
cout <<c<< endl;
return 0;
}
正常输出
#include <iostream>
using namespace std;
int main()
{
string c = "中";
cout <<c<< endl;
return 0;
}
这样自然也是没有问题的
也是乎有人问
char c = '\027'; 占了几个字节
不用多想 1个 由于 这是一个转义字符 所以就代表着一个普通字符而已
#include <stdio.h>
#include <stdlib.h>
int main()
{
char c = '\027';
printf("%c",c);
return 0;
}