“字节”是byte,“位”是bit ; (引荐进修:java课程)
1 byte = 8 bit ;
char 在Java中是2个字节。java采纳unicode,2个字节(16位)来示意一个字符。
例子代码以下:
public class Test { public static void main(String[] args) { String str= "中"; char x ='中'; byte[] bytes=null; byte[] bytes1=null; try { bytes = str.getBytes("utf-8"); bytes1 = charToByte(x); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("bytes 大小:"+bytes.length); System.out.println("bytes1大小:"+bytes1.length); } public static byte[] charToByte(char c) { byte[] b = new byte[2]; b[0] = (byte) ((c & 0xFF00) >> 8); b[1] = (byte) (c & 0xFF); return b; } }
运转效果:
bytes 大小:3 bytes1大小:2
java是用unicode来示意字符,"中"这个中文字符的unicode就是2个字节。
String.getBytes(encoding)要领是猎取指定编码的byte数组示意,一般gbk/gb2312是2个字节,utf-8是3个字节。
假如不指定encoding则取体系默许的encoding。
以上就是java字符占几个字节的细致内容,更多请关注ki4网别的相干文章!