---
title: "Java中有关byte和String的转换笔记"
author: "angushj"
date: "2007-10-25T13:54:09Z"
tags: ["C", "C#", "C++", "J#", "Java"]
slug: "java-byte-string"
draft: false
lastmod: "2007-10-25T13:54:09Z"
id: 135427
url: "https://angushj.iteye.com/blog/135427"
---

问题1：java中没有实现这种“byte a = 0xB2 --&gt; String b = “B2””转换的简单实现需要自己实现。  
答：自己编写的转换函数，思路将byte的高低4位分开，分别转换为对应的字符然后合成返回的字符串。

java 代码

01. public static String byteToString(byte b) {
02. byte high, low;
03. byte maskHigh = (byte)0xf0;
04. byte maskLow = 0x0f;
05. high = (byte)((b & maskHigh) &gt;&gt; 4);
06. low = (byte)(b & maskLow);
07. StringBuffer buf = new StringBuffer();
08. buf.append(findHex(high));
09. buf.append(findHex(low));
10. return buf.toString();
11. }
12. private static char findHex(byte b) {
13. int t = new Byte(b).intValue();
14. t = t &lt; 0 ? t + 16 : t;
15. if ((0 &lt;= t) &&(t &lt;= 9)) {
16. return (char)(t + '0');
17. }
18. return (char)(t-10+'A');
19. }

未解决的疑问在java中不存在类似C中的无符号量，所以如果一个字节超过0x80其对应的整型值即为负值，但在高位右移4位后还是负值，且与对应的正值相差16，比如0xB2经过右移后的期望值是0x0B（11）但实际值是－5与预期的值相差16（这个16通过多次试验得出），对此现象为找到合理的解释。

 

问题2：“String a=”B2” --&gt; byte b=0xB2”字符的byte转换为byte数据类型  
答：思路通过Integer作为转换的中间桥梁

java 代码

01. public static int stringToByte(String in, byte\[] b) throws Exception {
02. if (b.length &lt; in.length() / 2) {
03. throw new Exception("byte array too small");
04. }
05. int j=0;
06. StringBuffer buf = new StringBuffer(2);
07. for (int i=0; i
08. buf.insert(0, in.charAt(i));
09. buf.insert(1, in.charAt(i+1));
10. int t = Integer.parseInt(buf.toString(),16);
11. System.out.println("byte hex value:" + t);
12. b\[j] = (byte)t;
13. i++;
14. buf.delete(0,2);
15. }
16. return j;
17. }

问题3：整数（表示范围限定为两个字节unsigned short）通过Integer.byteValue()转换成byte\[2]，如果超出一个byte的表示范围将会截断高位的值。  
答：思路一个byte能表示的最大整数为256（超过128为负值，超过256将被截断），所以取256的倍数为byte\[0]，256的余数为byte\[1]。

java 代码

1. byte\[] d = new byte\[l+2];
2. ….
3. buff.put(new Integer(l/256).byteValue());
4. buff.put(new Integer(l%256).byteValue());