2

I'm working with ZigBee, I receive data from a sensor of a end device, and I want to convert from hex to int. The data are from 4bytes, this information is regarding the battery, an example of what I get would be this: "00 00 00 e1" (but without blanks) and I need to pass this on to voltages, but first I think I need to pass it to int.

Anyone can help me please? I'm doing my application for Android.

Thank you in advance.

Despotars
  • 541
  • 1
  • 8
  • 23
  • Are you receiving a string (`"000000e1"`) or a byte array (`0x00, 0x00, 0x00, 0xe1`)? You'll end up using different code to process each representation into a big-endian 32-bit unsigned integer. – tomlogic Sep 16 '13 at 19:56

3 Answers3

3

Use Integer.parseInt() for this:

Parses the string argument as a signed integer in the radix specified by the second argument

Example:

Integer.parseInt("-FF", 16) // pass 16 to indicate an hexadecimal value
=> -255
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thank you for your response, then, I can use this function to get the data into int, then only I have to pass it to voltage does not? – Despotars Sep 16 '13 at 16:14
  • 1
    @Despotars I don't understand your question. This function will convert from hex to int. Likewise, the function`Integer.toString()` will convert from int to hex. Use them as needed. – Óscar López Sep 16 '13 at 16:50
3
int n = (int)Long.parseLong(st.replaceAll("\\s+",""), 16);

(where st is your string) does it. Two things:

The replaceAll strips out any white space.

I go via the Long parser to circumvent NumberFormatExceptions for negatives

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Thank you for you response, When I receive the information I have no blanks, you tell me you pass the 8 characters and with that I would transform function to int? – Despotars Sep 16 '13 at 16:12
  • Your example contains whitespace so I assumed you needed to parse that. Without the spaces you can just do `int n = (int)Long.parseLong(st, 16);`, again going through `Long` to circumvent `NumberFormatExceptions` for negatives. – Bathsheba Sep 16 '13 at 16:15
1
Integer.parseInt("ff0000", 16)
Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61