Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert integer to hex signed 2's complement:

Pretty basic stuff i am sure but bits are not my forte.

So for some internal calculation i am trying to convert a given input ( constraint is that it would be a integer string for sure) into its hex equivalent, what stumped me is on how to get Hex signed 2's complement:

My noob code:

   private String toHex(String arg, boolean isAllInt) {
        String hexVal = null;
        log.info("arg {}, isAllInt {}", arg, isAllInt);
        if (isAllInt) {
            int intVal = Integer.parseInt(arg);
            hexVal = Integer.toHexString(intVal);
            // some magic to convert this hexVal to its 2's compliment
        } else {
            hexVal = String.format("%040x", new BigInteger(1, arg.getBytes(StandardCharsets.UTF_8)));
        }
        log.info("str {} hex {}", arg, hexVal);
        return hexVal;
    }

Input: 00001
Output: 1
Expected Output: 0001

Input: 00216
Output: D8
Expected Output: 00D8

00216

Input: 1192633166
Output: 4716234E
Expected Output: 4716234E

any predefined library is much welcome or any other useful pointers!

like image 227
NoobEditor Avatar asked May 23 '26 10:05

NoobEditor


1 Answers

So to pad the hex digits up to either 4 digits or 8 digits, do:

int intVal = Integer.parseInt(arg);
if (intVal >= 0 && intVal <= 0xffff) {
     hexVal = String.format("%04x", intVal);
} else {
     hexVal = String.format("%08x", intVal);
}

See Java documentation on how the format strings work.

like image 153
nos Avatar answered May 26 '26 00:05

nos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!