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
-
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.Mike 'Pomax' Kamermans– Mike 'Pomax' Kamermans2022年01月06日 05:12:10 +00:00Commented 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.user555045– user5550452022年01月06日 05:36:29 +00:00Commented 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 complementTejas Gohil– Tejas Gohil2022年01月06日 05:41:57 +00:00Commented 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 stepuser555045– user5550452022年01月06日 05:58:04 +00:00Commented 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.Community– Community Bot2022年01月13日 11:40:03 +00:00Commented Jan 13, 2022 at 11:40
1 Answer 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 & 0xffexpression strips off the sign extension. - The
"%02X"format says uppercase hexadecimal (X) in a 2 character field. The0means zero padded. Read Format String Syntax for more information.
answered Jan 6, 2022 at 5:56
Stephen C
724k95 gold badges849 silver badges1.3k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-java