日期:2014-05-20  浏览次数:20809 次

关于一个进制与ASCII转换的问题
现在要做这样一个东西
String str=0;

现有一方法是把mac转为电文,方法为
 public static String toHexString(byte[] content, int len) 
  {
  String hexString = "";
  for (int i = 0; i < len; i++) 
  {
  String temp = "";
  temp = Integer.toHexString(content[i] & 0x000000ff);
  if (temp.length() < 2) 
  {
  temp = "0" + temp;
  }
  temp += " ";
  hexString += temp;
  }
  return hexString;
  }

  String abc=toHexString(mac.getBytes(),mac.getBytes().length);
System.out.println(abc)
打印结果30
其实就是说0的十六进制的ASCII为30
我如果让str=":"
打印出的结果就为3a
如果让str="d";
打印结果就为64

现在我想把这个方法反着写,就是说
我传个30,想让它输出0
传个3a,想让它输出为(冒号):
传个64,想让它输出为d
这个方法要怎么写,或者有没有其它方法实现,急用。。谢谢各位,分一定会给,别叫我在网上找。。我找了,找不到。。。

------解决方案--------------------
Java code

    public static char reHex(byte[] content, int len) {
        byte[] bs = new byte[len];
        for (int i=0; i<len; i++) bs[i] = content[i];
        String s = new String(bs);
        int x = Integer.parseInt(s, 16);
        return (char)x;
    }
    
    public static void main(String[] args) {
        //测试
        byte[] bs = new byte[2];
        bs[0] = '6';
        bs[1] = '4';
        System.out.println(reHex(bs,2));
    }

------解决方案--------------------
public class Ascii2Number {
public static void main(String[] args) {
System.out.println(toAsciiHexCode( ': ') );
System.out.println(toAsciiHexCode( "toAsciiHexCode ") );
}

private static String toAsciiHexCode(String str) {
if (null == str) return " ";

StringBuilder builder = new StringBuilder();
for (int i=0; i < str.length(); i++) {
builder.append(toAsciiHexCode(str.charAt(i))).append( " ");
}

return builder.toString();
}
private static String toAsciiHexCode(char ch) {
return Integer.toHexString(48 + ch - '0 ').toUpperCase();
}
}


3A
74 6F 41 73 63 69 69 48 65 78 43 6F 64 65
------解决方案--------------------
我理解错你的意思了,其实你只是要个ASCII码而已,这个很容易实现。2楼给出的就是解决方案了。