2 Replies - 3256 Views - Last Post: 14 October 2009 - 11:48 PM

#1 born2c0de   User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 187
  • View blog
  • Posts: 4,673
  • Joined: 26-November 04

Decimal to Hex Convertor

Posted 27 February 2005 - 03:23 AM

Description: Execute from command line.Converts a Decimal Number into Hexadecimal through the Command Line without using the (s)printf function conversion.
#!perl
    #Get arguments from command line
    ($dec)[email protected];
    #Check for invalid info
    unless($dec) {
    print "nrUsage: $0  nr";
    exit();
    }
    # print decimal
    print "decimal number is: $decnr";
    # convert to hex and print results
    $hex = dec2hex($dec);
    print "hex number is: $hexnr";
    exit;
    sub dec2hex {
    # parameter passed to
    # the subfunction
    my $decnum = $_[0];
    # the final hex number
    my $hexnum;
    my $tempval;
    while ($decnum != 0) {
    # get the remainder (modulus function)
    # by dividing by 16
    $tempval = $decnum % 16;
    # convert to the appropriate letter
    # if the value is greater than 9
    if ($tempval > 9) {
    $tempval = chr($tempval + 55);
    }
    # 'concatenate' the number to 
    # what we have so far in what will
    # be the final variable
    $hexnum = $tempval . $hexnum ;
    # new actually divide by 16, and 
    # keep the integer value of the 
    # answer
    $decnum = int($decnum / 16); 
    # if we cant divide by 16, this is the
    # last step
    if ($decnum < 16) {
    # convert to letters again..
    if ($decnum > 9) {
    $decnum = chr($decnum + 55);
    }
    
    # add this onto the final answer.. 
    # reset decnum variable to zero so loop
    # will exit
    $hexnum = $decnum . $hexnum; 
    $decnum = 0 
    }
    }
    return $hexnum;
    } # end sub



Is This A Good Question/Topic? 0
  • +

Replies To: Decimal to Hex Convertor

#2 harston   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 28-August 08

Re: Decimal to Hex Convertor

Posted 28 August 2008 - 07:29 AM

Small random MAC address generator: #!/usr/bin/perl use strict; use warnings; my $count=0; while ( $count < 6 ) { my $num = int rand 255; my $hex = sprintf ("%X", $num); $hex = "0".$hex if ( $num < 17); $count < 5 ? print $hex.":" : print $hex."\n"; $count++ }
Was This Post Helpful? 0
  • +
  • -

#3 OmnipotentEntity   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 0
  • Joined: 15-October 09

Re: Decimal to Hex Convertor

Posted 14 October 2009 - 11:48 PM

... This is so atrociously bad, you're giving perl a bad rap. $hexstring = sprintf("%x",$number);
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1