java 数据类型与基本编码

java 采用Unicode来表示字符,每个字符(包括中文字符)都有两个字节

如下是java基本类型的字节数,注意不要与C的弄混了

int         4       最大值 0x7fffffff 2147483647=2的31次方-1  首位为符号位   最小值-2147483648  0x80000000  补码存储 首位不变 其他位取反后加1

short     2      最大值2^15-1  32767  最小值-2^15  -32768

long       8     最大值2^63-1    最小值-2^63  

byte       1     最大值2^7-1  127  最小值-2^7  -128

float       4

double    8

char       2

boolean  2

gb2312/gbk  都是两个字节,UTF-8是三个字节

如:

public class Test {


    public static void main(String[] args) {
        char x ='中';
        String str= "中";
        String c="c";
        String n="5";
        byte[] bytes=null;
        byte[] bytes1=null;
        byte[] bytes2=null;
        byte[] bytes3=null;
        byte[] bytes4=null;
        byte[] bytes5=null;
        byte[] bytes6=null;
        try {
            bytes = charToByte(x);
            bytes1=str.getBytes("gb2312");
            bytes2=str.getBytes();
            bytes3=c.getBytes("gb2312");
            bytes4=c.getBytes();
            bytes5=n.getBytes("gb2312");
            bytes6=n.getBytes();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("字符占:"+bytes.length);
        System.out.println("中文国标:"+bytes1.length);
        System.out.println("中文UTF-8:"+bytes2.length);
        System.out.println("字母国标:"+bytes3.length);
        System.out.println("字母UTF-8:"+bytes4.length);
        System.out.println("数字国标:"+bytes5.length);
        System.out.println("数字UTF-8:"+bytes6.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; 
    }
}

运行结果:

字符占:2
中文国标:2
中文UTF-8:3
字母国标:1
字母UTF-8:1
数字国标:1
数字UTF-8:1

本机eclipse  的编码设置为 UTF-8,  所以这里是三个字节

小弟菜鸟一枚,初来乍到,有什么错误还望各位大神不吝指出,^_^。
原文地址:https://www.cnblogs.com/maydow/p/4465018.html