简体   繁体   English

如何将String转换为十六进制?

[英]How to convert String to hex?

I have a TCP Client running on Android. 我有一个在Android上运行的TCP客户端。 The Server is an OBD2 Dongle. 该服务器是OBD2加密狗。 I am getting an InputStream which is saved in a String but it's a hex number. 我得到一个InputStream,它保存在String中,但是它是一个十六进制数字。

The Response of the TCP Server looks like that: FD A8 F1 FF 1F D0 03 20 It is a 8byte long hex number but I it is sent as a String, so I need to convert it to hex. TCP服务器的响应如下所示:FD A8 F1 FF 1F D0 03 20这是一个8字节长的十六进制数字,但是我以字符串形式发送,因此我需要将其转换为十六进制。

How can I do that? 我怎样才能做到这一点?

Edit: 编辑:

InputStream is; 

is = socket.getInputStream(); 

while(var_Receive){

BufferedReader rd = new BufferedReader(new InputStreamReader(is); 

String line = rd.readLine(); 

System.out.prinln(line); 

} 

And this is exactly what I see on screnn 'FD A8 F1 FF 1F D0 03 20' including the spaces between. 这正是我在screnn'FD A8 F1 FF 1F D0 03 20'上看到的内容,包括它们之间的空格。

试试这个:Integer.toHexString(Integer.parseInt(String));

Try the below code it will work. 试试下面的代码,它将起作用。 The value printed in console is in hexadecimal format. 在控制台中打印的值是十六进制格式。 Store it if you want to use it later. 如果要以后使用,请存储它。

public static void stringToHex(){

    String hexStr = "FD A8 F1 FF 1F D0 03 20";
    char[] chars = hexStr.toCharArray();

      StringBuffer hex = new StringBuffer();
      hex = new StringBuffer("0x");
      int  i =0;
      while(i<chars.length){
          if(chars[i]==' '){
              i++;
              //you can store this value if you want
              System.out.println(hex.toString());
              hex = new StringBuffer("0x");
              continue;
          }
          hex.append(chars[i]);
          i++;
      }
}

Shorter implementation according to requirement: 根据要求缩短实施时间:

String hexStr = "FD A8 F1 FF 1F D0 03 20";
String[] hexStrs = hexStr.split(" ");
DecimalFormat df = new DecimalFormat("#.00");
Double[] values = new Double[hexStrs.length];
for(int i=0; i<hexStrs.length; i++){
    values[i] = Double.valueOf(df.format(Integer.valueOf(hexStrs[i], 16)*0.04));
    System.out.println(values[i]);
}

Do the values in the hex representation represent a single value? 十六进制表示中的值代表单个值吗? If so: 如果是这样的话:

String hexStr = "FD A8 F1 FF 1F D0 03 20";
String hexNoSpace = hexStr.Replace(" ", string.Empty);

long valAsLong = long.Parse(hexNoSpace, NumberStyles.AllowHexSpecifier);
ulong valAsUnsignedLong = ulong.Parse(hexNoSpace, NumberStyles.AllowHexSpecifier);

result: 结果:

as long: -168618907973713120 只要:-168618907973713120

as ulong: 18278125165735838496 如乌龙:18278125165735838496

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM