01.public class Test {
02.
03.
04. public static void main(String[] args) {
05. String str= "中";
06. char x ='中';
07. byte[] bytes=null;
08. byte[] bytes1=null;
09. try {
10. bytes = str.getBytes("utf-8");
11. bytes1 = charToByte(x);
12. } catch (UnsupportedEncodingException e) {
13. // TODO Auto-generated catch block
14. e.printStackTrace();
15. }
16. System.out.println("bytes 大小:"+bytes.length);
17. System.out.println("bytes1大小:"+bytes1.length);
18. }
19. public static byte[] charToByte(char c) {
20. byte[] b = new byte[2];
//将c的高8位取出,然后右移运算8位
21. b[0] = (byte) ((c & 0xFF00) >> 8);
22. b[1] = (byte) (c & 0xFF);
23. return b;
24. }
25.}
02.
03.
04. public static void main(String[] args) {
05. String str= "中";
06. char x ='中';
07. byte[] bytes=null;
08. byte[] bytes1=null;
09. try {
10. bytes = str.getBytes("utf-8");
11. bytes1 = charToByte(x);
12. } catch (UnsupportedEncodingException e) {
13. // TODO Auto-generated catch block
14. e.printStackTrace();
15. }
16. System.out.println("bytes 大小:"+bytes.length);
17. System.out.println("bytes1大小:"+bytes1.length);
18. }
19. public static byte[] charToByte(char c) {
20. byte[] b = new byte[2];
//将c的高8位取出,然后右移运算8位
21. b[0] = (byte) ((c & 0xFF00) >> 8);
22. b[1] = (byte) (c & 0xFF);
23. return b;
24. }
25.}
本文展示了如何在Java中将字符转换为字节数组,并计算其长度,使用了标准的字符串操作和字节转换方法。
168万+

被折叠的 条评论
为什么被折叠?



