研究问题的起因
业务A调用业务B的接口,通过http调用。参数很大,需要预估一下参数的大小,以便设置一个参数的数组的最大值。
示例代码
public static void main(String[] args) throws UnsupportedEncodingException {
String a = "abc";
byte[] defaultBytes = a.getBytes();
byte[] utf8Bytes = a.getBytes("utf-8");
byte[] unicodeBytes = a.getBytes("unicode");
byte[] gbkBytes = a.getBytes("gbk");
byte[] unicodeLittleBytes = a.getBytes("UnicodeLittleUnmarked");
byte[] unicodeBigBytes = a.getBytes("UnicodeBigUnmarked");
System.out.println("defaultBytes : " + Arrays.toString(defaultBytes) + " length: " + defaultBytes.length);
System.out.println("utf8Bytes : " + Arrays.toString(utf8Bytes) + " length: " + utf8Bytes.length);
System.out.println("gbkBytes : " + Arrays.toString(gbkBytes) + " length: " + gbkBytes.length);
System.out.println("unicodeBytes : " + Arrays.toString(unicodeBytes) + " length: " + unicodeBytes.length);
System.out.println("unicodeBigBytes : " + Arrays.toString(unicodeBigBytes) + " length: " + unicodeBigBytes.length);
System.out.println("unicodeLittleBytes: " + Arrays.toString(unicodeLittleBytes) + " length: " + unicodeLittleBytes.length);
}
输出结果:
defaultBytes : [97, 98, 99] length: 3
utf8Bytes : [97, 98, 99] length: 3
gbkBytes : [97, 98, 99] length: 3
unicodeBytes : [-2, -1, 0, 97, 0, 98, 0, 99] length: 8
unicodeBigBytes : [0, 97, 0, 98, 0, 99] length: 6
unicodeLittleBytes: [97, 0, 98, 0, 99, 0] length: 6
字符串占用的内存大小是传输时的字符集相关的。默认的字符集是utf8,可以通过String.getBytes()方法的实现查看。
utf8:ascii码用一个字节。
特殊说明
unicode字符集获取到的字节多了两个字节: -2, -1。这表示字节序。
unicode默认是UnicodeBigUnmarked字节序。
网友评论