ITeye博客

Java中有关byte和String的转换笔记

angushj · 2007-10-25 13:54 · Java技巧 · C · Java · C++ · J# · C# · Markdown

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

java 代码

  1. public static String byteToString(byte b) {
  2. byte high, low;
  3. byte maskHigh = (byte)0xf0;
  4. byte maskLow = 0x0f;
  5. high = (byte)((b & maskHigh) >> 4);
  6. low = (byte)(b & maskLow);
  7. StringBuffer buf = new StringBuffer();
  8. buf.append(findHex(high));
  9. 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 < 0 ? t + 16 : t;
  15. if ((0 <= t) &&(t <= 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” --> byte b=0xB2”字符的byte转换为byte数据类型
答:思路通过Integer作为转换的中间桥梁

java 代码

  1. public static int stringToByte(String in, byte[] b) throws Exception {
  2. if (b.length < in.length() / 2) {
  3. throw new Exception("byte array too small");
  4. }
  5. int j=0;
  6. StringBuffer buf = new StringBuffer(2);
  7. for (int i=0; i
  8. buf.insert(0, in.charAt(i));
  9. 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());

评论(1)

  1. #1 楼 · bigboy · 2010-09-02 10:43

    b & maskHigh) >> 4是有符号右移,若符号为负,高位补1,b & maskHigh) >>> 4是无符号右移,高位补0,就可以得到你想要的期望值了,0x0B(11)

评论功能维护中,当前仅展示历史评论。