Java 中字符串的字节数
在Java中,如果我有一个字符串,如何计算该字符串中的字节数?x
字符串是字符(即码位)的列表。用于表示字符串的字节数完全取决于您用于将其转换为字节的编码。
也就是说,您可以将字符串转换为字节数组,然后按如下方式查看其大小:
// The input string for this test
final String string = "Hello World";
// Check length, in characters
System.out.println(string.length()); // prints "11"
// Check encoded sizes
final byte[] utf8Bytes = string.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "11"
final byte[] utf16Bytes= string.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "24"
final byte[] utf32Bytes = string.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "44"
final byte[] isoBytes = string.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "11"
final byte[] winBytes = string.getBytes("CP1252");
System.out.println(winBytes.length); // prints "11"
所以你看,即使是一个简单的“ASCII”字符串,其表示形式也可能具有不同的字节数,具体取决于使用的编码。使用您感兴趣的任何字符集作为 您的案例的参数。不要陷入假设 UTF-8 将每个字符表示为单个字节的陷阱,因为那也不是真的:getBytes()
final String interesting = "\uF93D\uF936\uF949\uF942"; // Chinese ideograms
// Check length, in characters
System.out.println(interesting.length()); // prints "4"
// Check encoded sizes
final byte[] utf8Bytes = interesting.getBytes("UTF-8");
System.out.println(utf8Bytes.length); // prints "12"
final byte[] utf16Bytes= interesting.getBytes("UTF-16");
System.out.println(utf16Bytes.length); // prints "10"
final byte[] utf32Bytes = interesting.getBytes("UTF-32");
System.out.println(utf32Bytes.length); // prints "16"
final byte[] isoBytes = interesting.getBytes("ISO-8859-1");
System.out.println(isoBytes.length); // prints "4" (probably encoded "????")
final byte[] winBytes = interesting.getBytes("CP1252");
System.out.println(winBytes.length); // prints "4" (probably encoded "????")
(请注意,如果未提供字符集参数,则使用平台的默认字符集。这在某些上下文中可能很有用,但通常应避免依赖默认值,并在需要编码/解码时始终使用显式字符集。
如果使用 64 位引用运行:
sizeof(string) =
8 + // object header used by the VM
8 + // 64-bit reference to char array (value)
8 + string.length() * 2 + // character array itself (object header + 16-bit chars)
4 + // offset integer
4 + // count integer
4 + // cached hash code
换句话说:
sizeof(string) = 36 + string.length() * 2
在 32 位 VM 或具有压缩 OOP (-XX:+UseCompressedOops) 的 64 位 VM 上,引用为 4 个字节。因此,总数将是:
sizeof(string) = 32 + string.length() * 2
这不考虑对字符串对象的引用。