Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am in need of below Java code converted to PERL script. Can anyone help me in this context?

PERL
<pre> public static String hex(byte[] bytes) {
    char[] c = new char[bytes.length * 2];
    for (int i = 0; i < bytes.length; i++) {
        int j = (bytes.length - i - 1) * 2;
        c[(j + 0)] = HEX[(bytes[i] >> 4 & 0xF)];
        c[(j + 1)] = HEX[(bytes[i] >> 0 & 0xF)];
    }
    return new String(c);
}


What I have tried:

i have no idea of PERL.Please help me in this regard.
Posted
Updated 29-May-18 3:45am
v2
Comments
CPallini 29-May-18 9:21am    
Is Perl mandatory? Cannot you use another scripting language?

1 solution

The first step is to understand what the code is doing:
The code seems to convert an array of bytes to a string of hex characters where the lowest byte is on the right side of the string (it depends on the definition of the HEX array but I guess it is just a mapping to the characters 0 to 9 and a to f).

You can then search the web for something like "perl hex array to string". Doing so, you will find solutions like perl - Convert an array of integer into a string of HEX - Stack Overflow[^].

From my point of view you should use one of the powerful Perl conversion functions: unpack - perldoc.perl.org[^]. If the input argument is an array, see the above SO link.

If it is any variable containing binary data, it is much simpler:
PERL
my( $hexString ) = unpack( 'H*', $bytes );

Example:
PERL
my $bytes = "123\x0A";
my( $hexString ) = unpack( 'H*', $bytes );
print "$hexString\n";
Output:
3132330a
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900