创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!
java中的char占几个字节实例分析
1:“字节”是byte,“位”是bit ;
2: 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; } }