0

i have a byte array its value taken from debugger

0 = -124
1 = 56
2 = 56
3 = 65

then convert to hex

StringBuilder res1 = new StringBuilder();
for (byte b : Bytes) {
    res1.append(String.format("%02X-", b));
}

i get result 84-38-38-41

,i want to revert it back to same previous value like

if i have 84-38-38-41 ,how can i get the bytearray with the value

0 = -124
1 = 56
2 = 56
3 = 65

means hex string to decimal array

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
android_guy
  • 152
  • 1
  • 2
  • 14
  • 1
    If you drop the '-' from your format, you can use: http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java. Or just modify it to skip the '-'. – Elist Jan 01 '17 at 05:57
  • thanks it works after modifying a bit – android_guy Jan 01 '17 at 06:01

2 Answers2

2

Replaced all "-" with "" and this does your job. I hope this will help.

        byte [] data = {-124,56,56,24};
        StringBuilder res1 = new StringBuilder();
        for (byte b : data) {
            res1.append(String.format("%02X-",b));
        }
        String new_String  = res1.toString().replaceAll("-", "");
        byte [] output = DatatypeConverter.parseHexBinary(new_String);
        for(int i = 0;i < output.length;i++){
            System.out.println(output[i]);
        }
SmashCode
  • 741
  • 1
  • 8
  • 14
0

Byte[] to hex:

public String getHex(byte[] raw) {
        final String HEXES = "0123456789abcdef";
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }

Hex to byte[]:*

public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

And remember... Always practice safe hex! (:

apt-getschwifty
  • 199
  • 2
  • 12