Striker1440 Striker1440 - 1 year ago 141
Perl Question

Pack h* equivalent in Java

Server side we have a Perl script that takes an uploaded PDF file and performs the following on it, after which the data is stored within an SQL database:

unpack ('h*', $fileData);

I'm writing a new Java based module that obtains the data from the database, and I need some way to get this data back into a PDF file.
The Perl equivalent is:

pack ('h*', $FileContents);

Is there an equivalent method that can be used in Java to achieve this?
Note: I cannot make any changes to the existing server side code.

Answer Source
// Takes hex string with low nibble first as produced by Perl's unpack 'h*'
// For example, 031323 => 0x30, 0x31, 0x32
public static byte[] hexLoHiStringToByteArray(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+0), 16) << 4)
            |  Character.digit(s.charAt(i+1), 16)

    return data;

(h* is such a weird choice over H*.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download