For my post yesterday on the HD-DVD key I needed to convert the 128bit HEX key into a decimal number and then divide it by two. I figured this would be easy. I’d wander over to Google, search for “convert hex to decimal” and hey-presto, I’d get a web-based converter somewhere to bang the hex key into and get out a decimal number. This soon proved not to work in practice for large numbers. All the converters I tried gave me back floating point numbers with very large exponents. The means loads of precision was lost and hence I couldn’t get the exact number the MPAA claimed to own. So I did what I always do when I can’t find a program to do what I want, I hacked something together in Perl! Now, when I say hacked I do mean hacked. It only took me a few minutes to do and what do ya know, Perl lost precision too, giving me an answer of 1.32562788879895e+37. So, I needed to re-implement this algorithm in a language that could give me basically unlimited integer arithmetic. I chose Java because of the java.math.BigInteger class and because Java is the language I know best. I implemented the same basic algorithm in both languages. It’s interesting to see just how much bigger the Java code is!

Technorati Tags: ,

The Algorithm

The algorithm was very simple and doubtless not ‘best practice’. Because my binary operator knowledge is very rusty I converted from HEX to binary using a lookup table (only took a minute or so to throw together a quick hash indexed by the 16 hex characters that contained the 16 equivalent binary strings). So, in one quick foreach loop the program converted the hex to a binary string, then the binary string was reversed, and finally looped through multiplying each binary digit by two to the power of its position in the string and all those results summed together for an answer. This is a very simple algorithm that’s easy to implement and that works. Remember, the aim in hacking a solution is to get an answer as quick as possible, not to write a great program!

Before we go any further lets have a look at the code.

The Perl Implementation

  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4.  
  5. my $hex = $ARGV[0];
  6. $hex =~ s/\-//g;
  7. my $bin = '';
  8. my $hexToBin = {
  9.   0 => '0000',
  10.   1 => '0001',
  11.   2 => '0010',
  12.   3 => '0011',
  13.   4 => '0100',
  14.   5 => '0101',
  15.   6 => '0110',
  16.   7 => '0111',
  17.   8 => '1000',
  18.   9 => '1001',
  19.   A => '1010',
  20.   B => '1011',
  21.   C => '1100',
  22.   D => '1101',
  23.   E => '1110',
  24.   F => '1111',
  25. };
  26.  
  27. foreach my $i (0..length($hex)){
  28.   $bin .= $hexToBin->{substr($hex, $i, 1)}
  29. }
  30.  
  31. print "Binary: $bin\n";
  32.  
  33. my $binRev = reverse($bin);
  34. my $ans = 0;
  35. foreach my $i (0..length($binRev)){
  36.   $ans += substr($binRev, $i, 1) * 2**$i;
  37. }
  38.  
  39. print "Decimal: $ans\n";

The Java Implementation

  1. import java.math.BigInteger;
  2.  
  3. public class hex2dec {
  4.   public static void main(String args[]) {
  5.     String hex = args[0].replaceAll("-", "");
  6.     String bin = hex2bin(hex);
  7.     System.out.println("Binary: " + bin);
  8.     BigInteger ans = bin2dec(bin);
  9.     System.out.println("Decimal: " + ans.toString());
  10.   }
  11.  
  12.   public static String hexCharToBinString(char h) {
  13.     switch (h) {
  14.         case '0':
  15.           return "0000";
  16.         case '1':
  17.           return "0001";
  18.         case '2':
  19.           return "0010";
  20.         case '3':
  21.           return "0011";
  22.         case '4':
  23.           return "0100";
  24.         case '5':
  25.           return "0101";
  26.         case '6':
  27.           return "0110";
  28.         case '7':
  29.           return "0111";
  30.         case '8':
  31.           return "1000";
  32.         case '9':
  33.           return "1001";
  34.         case 'A':
  35.           return "1010";
  36.         case 'B':
  37.           return "1011";
  38.         case 'C':
  39.           return "1100";
  40.         case 'D':
  41.           return "1101";
  42.         case 'E':
  43.           return "1110";
  44.         case 'F':
  45.           return "1111";
  46.     }
  47.     return "";
  48.   }
  49.  
  50.   public static String hex2bin(final String hex) {
  51.     StringBuffer ans = new StringBuffer();
  52.     for(int i = 0; i < hex.length(); i++) {
  53.       ans.append(hexCharToBinString(hex.charAt(i)));
  54.     }
  55.     return ans.toString();
  56.   }
  57.  
  58.   public static BigInteger bin2dec(final String b) {
  59.     BigInteger ans = new BigInteger("0");
  60.     String binRev = ((new StringBuffer(b)).reverse()).toString();
  61.     for(int i = 0; i < binRev.length(); i++) {
  62.       ans = ans.add(binCharToBigInt(binRev.charAt(i)).multiply(twoToThePowerOf(i)));
  63.     }
  64.     return ans;
  65.   }
  66.  
  67.   public static BigInteger binCharToBigInt(char b) {
  68.     if(b == '1') {
  69.       return new BigInteger("1");
  70.     }
  71.     return new BigInteger("0");
  72.   }
  73.  
  74.   public static BigInteger twoToThePowerOf(int n) {
  75.     if(n == 0) {
  76.       return new BigInteger("1");
  77.     }
  78.     if(n == 1) {
  79.       return new BigInteger("2");
  80.     }
  81.     BigInteger ans = new BigInteger("2");
  82.     for(int i = 1; i < n; i++) {
  83.       //ans *= 2;
  84.       ans = ans.multiply(new BigInteger("2"));
  85.     }
  86.     return ans;
  87.   }
  88. }

Some Points I Noted

As the title suggests, this is not even a remotely scientific comparison. But I do just want to point out some things that struck me while implementing the same algorithm in the two languages one after the other.

  1. Size - Well, if you’re surprised that the Perl implementation is a lot shorter you probably don’t know very much about Perl :) However, in this case the solution in Java is well over twice as long (38 lines v 88 lines).
  2. Data Structures - It’s far easier to create a simple hash in Perl. I Java you have to jump through too many hoops with boxing and un-boxing so I didn’t even bother and just used a function with a switch statement.
  3. Loops - I find the Perl foreach loops a lot simpler to understand at a glance.
  4. Operators - It’s easier to see what’s going on in the Perl loops thanks to the range operator (..). Raising two to the power of i is also easier in Perl because of the ** operator. Java is missing both these operators. Java does have power functions via the java.lang.Math but this function uses floating point arithmetic and hence is no good for integer maths. So, I had to implement my own function for raising two to the appropriate power.
  5. String Manipulation - The Java String class is missing some pretty basic functionality, including a function for reversing it. In Perl this is trivial, there is a built in reverse function! In Java I had to temporarily convert my String to a StringBuffer to reverse it. This is responsible for the following very ugly line of code:

    String binRev = ((new StringBuffer(b)).reverse()).toString();

Comments

3 Responses to “A Non-Scientific Comparison of Java and Perl”

  1. Koen Vervloesem on May 4th, 2007 5:37 pm

    If you only wanted to convert the number from hexadecimal to decimal, you could have used Ruby:

    irb(main):001:0> “09F911029D74E35BD84156C5635688C0″.hex
    => 13256278887989457651018865901401704640

    Of course, writing your own algorithms is a lot more fun! :-)

  2. Bart B on May 4th, 2007 5:41 pm

    Well … since I don’t know ruby it would have taken me quite a while to do it that way ;)

  3. Danny Rathjens on March 19th, 2010 3:13 am

    perl has a hex function and BigNumber support, too. :)
    % perl -Mbignum -wle’print hex pop’ 09F911029D74E35BD84156C5635688C0
    13256278887989457651018865901401704640

Leave a Reply




Before you post a comment please remember that commenting on my blog is a privilege not a right. I won't approve comments that are obscene, offensive or insulting. For more info please read this post.

Subscribe without commenting