0

i am receving sensor data which sends me Decimal from signed 2's complement want to convert it to hex decimal without signed 2's complement

5
  • And what did you find/write already to achieve that goal? Because SO is here to help you solve problems with your code, it's not a general help forum for when you have an idea but haven't done anything about it yet. Give how to ask a good question a read-through, and then update your post accordingly. Commented Jan 6, 2022 at 5:12
  • Most things in this question make no sense to me, or are impossible. Maybe I'm wrong, but I expect that the sensor doesn't send data in decimal (a common cause for this confusion is that integers are printed in decimal by default, but that doesn't mean that the integer is decimal, it's just printed that way), but send data as a raw signed byte (which you can print in hexadecimal). Please clarify. Commented Jan 6, 2022 at 5:36
  • yes you are right its sends in byte but there is a default file provided by sensor manufacturer so thats decode the bytes and gives me Decimal from signed 2's complement Commented Jan 6, 2022 at 5:41
  • Do you have to use that default file? It's still possible to convert from a decimal representation, but that's an avoidable extra step Commented Jan 6, 2022 at 5:58
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Commented Jan 13, 2022 at 11:40

1 Answer 1

1
String decimal = "-73";
int number = Integer.parseInt(decimal);
String unsignedHex = String.format("%02X", number & 0xff);

The parseInt call converts the signed decimal string to a (signed) int value.

The format call converts the int to an unsigned byte string in uppercase hexadecimal:

  • The number & 0xff expression strips off the sign extension.
  • The "%02X" format says uppercase hexadecimal (X) in a 2 character field. The 0 means zero padded. Read Format String Syntax for more information.
answered Jan 6, 2022 at 5:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.